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>
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With