Home > OS >  Google map directions between two routes using Ionic @capacitor/google-maps
Google map directions between two routes using Ionic @capacitor/google-maps

Time:02-04

I'm building a taxi app where I need to display the direction between two location. When customer clicks on navigate I need to do live tracking just like google maps app.

Below is what I've done so far,

//Getting current location of the user

this.coordinates = await Geolocation.getCurrentPosition();

// Creating the map

this.newMap = await GoogleMap.create({
  id: 'my-map',
  element: this.mapRef.nativeElement,
  apiKey: APIKEY,
  config: {
    center: {
      lat: 33.6,
      lng: -117.9,
    },
    zoom: 8,
  },
});

Now, How do I implement the live tracking feature ? Please help me with basic setup.

CodePudding user response:

  1. you need to add a geolocation listener to grab the location when it changes.
  2. push that new location to an array and display that location on the map.

CodePudding user response:

You can use https://github.com/apache/cordova-plugin-geolocation

navigator.watchPosition().subscribe((resp) => {
  this.latitude = resp.coords.latitude;
  this.longitude = resp.coords.longitude;

  if (!this.marker) {
    this.marker = new google.maps.Marker({
      position: new google.maps.LatLng(this.latitude, this.longitude),
      map: this.map,
      title: 'Current Location'
    });
  } else {
    this.marker.setPosition(new google.maps.LatLng(this.latitude, this.longitude));
  }
});

The watchPosition() method subscribe to updates in the device's location. The if statement checks if the marker object exists, and if it doesn't, it creates a new marker. If the marker object already exists, the marker's position is updated.

This is just a basic example, you can customize the marker by adding icon and other stuff.

Don't forget to addd needed permissions for iOS and Android.

  • Related