Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click on Google Maps API and get the address

The following code allows to get the coordinates, on click. But how to get the address or city name or region name or country on click on the map, with Google Maps API?

var myLatlng = new google.maps.LatLng(41.38,2.18);
var myOptions = { zoom: 13, center: myLatlng}
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

google.maps.event.addListener(map, 'click', function(event) {alert(event.latLng);});
html, body, #map-canvas {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>
<div id="map-canvas"></div>
like image 992
Basj Avatar asked Apr 27 '16 14:04

Basj


People also ask

How do I pull an address from Google Maps?

What's the address? is a simple tool that can help you find the approximate address of any point on Google Maps. All you have to do is drag the red marker pin to another location and the approximate snail address of that place should pop-up in a marker window.

How do I create an autocomplete address field in Google Maps API?

First, enable Google Places API Web Service. Get the API key. You will have to use it in the script tag in html file. Use script file to load the autocomplete class.

Is Google address lookup API free?

Even though the Google Maps API is free, it does not actually validate addresses, AND it comes with some pretty restrictive terms of service. So, if real address validation is what you need, you may want to read our review on how to choose an address validation provider.


1 Answers

You can pass the event.latLng trough the Geocoder to get the address:

var myLatlng = new google.maps.LatLng(41.38, 2.18);
var myOptions = {
  zoom: 13,
  center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var geocoder = new google.maps.Geocoder();

google.maps.event.addListener(map, 'click', function(event) {
  geocoder.geocode({
    'latLng': event.latLng
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0]) {
        alert(results[0].formatted_address);
      }
    }
  });
});

Fiddle

like image 102
putvande Avatar answered Sep 29 '22 06:09

putvande