How to draw a line between two points (Latitude and Longitude) with the Google map API using jQuery or Javascript? I need the shortest path between the two points. It may be any type of line.
A polyline is a list of points, where line segments are drawn between consecutive points. A polyline has the following properties: Points.
Here's an API v3 way of drawing a line.
var line = new google.maps.Polyline({
path: [
new google.maps.LatLng(37.4419, -122.1419),
new google.maps.LatLng(37.4519, -122.1519)
],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 10,
map: map
});
This simply draws a straight line between two points. If you want it to be the shortest path, you need to account for the fact that the earth is curved, and draw a geodesic line. To do that, you have to use the geometry library in the Google Maps API, by adding this optional libraries parameter:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
And then just add geodesic: true
to the options for your Polyline:
var line = new google.maps.Polyline({
path: [new google.maps.LatLng(37.4419, -122.1419), new google.maps.LatLng(37.4519, -122.1519)],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 10,
geodesic: true,
map: map
});
For API v2 only!
The following code snippet creates a 10-pixel-wide red polyline between two points:
var polyline = new GPolyline([
new GLatLng(37.4419, -122.1419),
new GLatLng(37.4519, -122.1519)],
"#ff0000", 10);
map.addOverlay(polyline);
You can find the documentation here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With