Search code examples
google-mapscordovaionic-frameworkionic3cordova-plugins

How can I draw a line between two google map native markers? (Ionic 3, cordova)


How can I draw a line between two google maps native markers? In my project, I need one dynamic marker and one fixed marker.

addMarker() {
  this.map.addMarker({
    title: 'My Marker',
    icon: 'blue',
    animation: 'DROP',
    position: {
      lat: this.place.lat,
      lng: this.place.lng
    }
  })
  .then(marker => {
    marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => {
      alert('Marker Clicked');
    });
  });
}

2nd marker:

addMarker2() {
          this.map.addMarker({
            title: 'My Marker',
            icon: 'blue',
            animation: 'DROP',
            position: {
              lat: -33,
              lng: 773231
            }
          })
          .then(marker => {
            marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => {
              alert('Marker Clicked');
            });
          });
        }

and how can I show route between the two markers using a line?

Thanks in advance,


Solution

  • The documentation for the Polyine class for cordova-plugin-googlemaps indicates you would add a Polyline between your markers like this:

    let points = [
        {
          lat: this.place.lat,
          lng: this.place.lng
        },
        {
          lat: -33,
          lng: 773231
        }
    ];
    
    this.map.addPolyline({
        points: points,
        'color' : '#AA00FF',
        'width': 10,
        'geodesic': true
    });
    

    This will draw a straight (geodesic) line between the markers.

    However in your question you asked "how can I show route between the two markers using a line". A travel route is of course not as simple as drawing a straight line from A to B - if you want to draw a detailed transport route, then it's a bit more complicated:

    The Google Maps Directions API enables you to calculate directions between locations and returns a JSON response which contains a detailed travel route, including an encoded polyline of the route which you can draw straight onto your map. The catch is that the Google APIs endpoint doesn't support CORS headers so if you make a request direct from your Cordova app, the Webview will block the response.

    So instead I would suggest including the Google Maps Javascript SDK in your Cordova app (even though you're using the native Google Maps plugin to show the maps) since this includes a directions service which can access the Google Maps Directions API and is not inhibited by CORS so can be used in your Cordova app.

    Similar to the Google Maps Directions API endpoint, it returns a JSON response detailing a travel route between locations, including an encoded polyline. You can easily decode the polyline using a library such as mapbox polyline then draw the resulting set of coordinates as a Polyline on your native Google Map to show a detailed travel route.