Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  81] [ 6]  / answers: 1 / hits: 34250  / 8 Years ago, wed, april 27, 2016, 12:00:00

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>




More From » google-maps

 Answers
65

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


[#62383] Monday, April 25, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adilene

Total Points: 395
Total Questions: 88
Total Answers: 109

Location: Indonesia
Member since Tue, Aug 3, 2021
3 Years ago
;