Understanding Google Maps Polylines
Google Maps polylines are a way to display multiple points on a map, often used for routes or paths. In this article, we’ll explore the technical details of how to create and display polylines using the Google Visualization API.
The Issue with lineWidth
The original code provided has an issue with the lineWidth option. According to the documentation, if showLine is true, lineWidth defines the line width in pixels. However, it seems that this option is ignored, and instead, there’s an undocumented option called lineWeight.
Finding the Solution
To fix the issue, we need to set the lineWeight option to a number greater than 0. The corrected code uses the following options:
showLine: true to display the linelineWeight: 20 to set the line width in pixels
The complete corrected code looks like this:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="map_div"></div>
<script>
google.load("visualization", "1", { packages: ["map"] });
google.setOnLoadCallback(drawMap);
function drawMap() {
var arr = [
['postcode', 'name'],
[
"77003",
"Houston"
],
[
"08540",
"Princeton"
],
[
"80545",
"Red Feather Lakes"
]
];
var data = google.visualization.arrayToDataTable(arr);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showLine: true,
lineWeight: 20,
lineColor: 'red',
enableScrollWheel: true
});
}
</script>
<style>
html, body, #map_div {
height: 100%;
padding: 0;
margin: 0;
}
</style>
Understanding the Code
The code above uses the Google Visualization API to create a map and display a polyline. Here’s a breakdown of what each part does:
- The first script tag loads the Google Visualization API.
- The second script tag sets up a callback function
drawMapthat will be executed when the API is loaded. - Inside the
drawMapfunction, an array is created to hold the data for the polyline. Each inner array represents a point on the polyline, with the first element being the postcode and the second element being the name. - The
google.visualization.arrayToDataTable()method is used to convert the array into a data table that can be used by the Google Visualization API. - A new instance of the
google.visualization.Mapclass is created, passing in the HTML element with the id “map_div” as the container for the map. - The
draw()method is called on the map instance, passing in the data table and an options object that specifies the line width, color, and other properties.
Conclusion
In conclusion, to display a polyline on Google Maps using the Google Visualization API, you need to use the correct option (lineWeight) instead of lineWidth. By understanding how to create and display polylines, developers can effectively visualize routes or paths on maps.
Last modified on 2024-04-30