Getting coordinates based on city name google map
Asked Answered
L

1

7

I am trying to create coordinates based on city with google maps, here is example what i have for now, i always get error?

var address = 'Zurich, Ch';

var geocoder = new google.maps.Geocoder();

geocoder.geocode({
  'address': address
}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    var Lat = results[0].geometry.location.lat();
    var Lng = results[0].geometry.location.lng();
  } else {
    alert("Something got wrong " + status);
  }
});

var myOptions = {
  zoom: 11,
  center: new google.maps.LatLng(Lat, Lng),
};
Lithea answered 19/1, 2016 at 13:16 Comment(1)
What error do you get?Eructate
E
10

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

related question: Using Address Instead Of Longitude And Latitude With Google Maps API

proof of concept fiddle

code snippet:

function initialize() {
  var address = 'Zurich, Ch';

  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var Lat = results[0].geometry.location.lat();
      var Lng = results[0].geometry.location.lng();
      var myOptions = {
        zoom: 11,
        center: new google.maps.LatLng(Lat, Lng)
      };
      var map = new google.maps.Map(
        document.getElementById("map_canvas"), myOptions);
    } else {
      alert("Something got wrong " + status);
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);
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>
Eructate answered 19/1, 2016 at 14:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.