Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google maps api geocoder is not working

I am trying to convert a zip code into lat and lng using geocoder. I looked at the Google Maps Api example and followed several tutorials, but for some reason for lat and lng it returns "". Here is my code.

(function(window, google, address) {
  var geocoder = new google.maps.Geocoder();
  var lat = "";
  var lng = "";
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    var test = results[0];
    lat = results[0].geometry.location.lat(); // lat is still equal to ""
    lng = results[0].geometry.location.lng(); // lng is still equal to ""
  });

  var options = {
      center: {
        lat: lat,
        lng: lng
      },
      zoom: 5
    },
    element = document.getElementById('map-canvas')
  var map = new google.maps.Map(element, options)
}(window, window.google, 98107));
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
like image 749
Aaron Avatar asked Oct 16 '25 17:10

Aaron


1 Answers

The geocoder is asynchronous. You need to use the data returned in the callback function when/where it exists.

(function(window, google, address) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    var options = {
        center: results[0].geometry.location,
        zoom: 5
      },
      element = document.getElementById('map-canvas')
    var map = new google.maps.Map(element, options)
  });
}(window, window.google, "98107"));

Another issue with the posted code is the address passed into the geocoder must be a string (so "98107", not 98107), if it isn't the API generates the error: InvalidValueError: in property address: not a string

(function(window, google, address) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    var options = {
        center: results[0].geometry.location,
        zoom: 5
      },
      element = document.getElementById('map-canvas')
    var map = new google.maps.Map(element, options)
  });

}(window, window.google, "98107"));
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
like image 50
geocodezip Avatar answered Oct 18 '25 06:10

geocodezip