Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a line between two point on a Google map using jQuery?

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.

like image 541
Vikas Avatar asked Nov 17 '12 18:11

Vikas


People also ask

What is a polyline on a map?

A polyline is a list of points, where line segments are drawn between consecutive points. A polyline has the following properties: Points.


2 Answers

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
});
like image 95
duncan Avatar answered Oct 11 '22 18:10

duncan


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.

like image 45
Gurpreet Singh Avatar answered Oct 11 '22 18:10

Gurpreet Singh