The reason why you are not getting the expected result is because in the above example there is a wrong placement of the code. You are trying to get a new instance of the Google Maps API Geocoder before Google Maps is fully loaded. Therefore, the Google Maps API Geocoder will not work because of this Uncaught ReferenceError: google is not defined . You should get a new instance of the geocoding of the Google Maps API in the initMap () function.
You can check the Maps JavaScript Geocoding API to find out more.
You can also check out Best Practices for Geocoding Addresses .
Also note that you should not specify your API_KEY when posting questions related to Google Maps APi.
Here is the whole code:
<!DOCTYPE html> <html> <head> <title>Geocoding service</title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> #map { height: 100%; } html, body { height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> var geocoder; var map; var address = "new york city"; function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 8, center: {lat: -34.397, lng: 150.644} }); geocoder = new google.maps.Geocoder(); codeAddress(geocoder, map); } function codeAddress(geocoder, map) { geocoder.geocode({'address': address}, function(results, status) { if (status === 'OK') { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } else { alert('Geocode was not successful for the following reason: ' + status); } }); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> </script> </body> </html>
Live demo here .
Hope this helps!
source share