Search code examples
angulargoogle-mapsleafletgeocodinggoogle-maps-urls

How to add Marker in google maps from leaflet geocoder


I am using leaflet-geosearch to search for longitude and latitude of an address which I show display in a google maps page, i am using angular

in my component

private openAddressInMap() {
    this.provider.search({query: address}).then(result => { // search coordinates for each city
      if (!isNullOrUndefined(result) && result.length > 0 && !isNullOrUndefined(result[0])) {
        const lng = result[0].x;
        const lat = result[0].y;
        window.open('https://maps.google.com/?q=' + lat + ',' + lng, '_blank');
      }
    });
}

then I open google maps link by passing lat and lng, the problem is the marker is not well positionned, it points on the wrong address


Solution

  • Do you really need get coordinates via geocoder? If you use Google Maps URLs, you can directly send address as a query parameter of URL and avoid geocoding request

    The code snippet is

    private openAddressInMap() {
        window.open('https://www.google.com/maps/search/?api=1&query=' + encodeURIComponent(address), '_blank');
    }
    

    Try for example the following URL:

    https://www.google.com/maps/search/?api=1&query=New+York

    I hope this helps!