【问题标题】:Getting coordinates based on city name google map根据城市名称谷歌地图获取坐标
【发布时间】:2016-01-19 13:16:01
【问题描述】:

我正在尝试使用谷歌地图创建基于城市的坐标,这是我现在拥有的示例,我总是出错?

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),
};

【问题讨论】:

  • 你得到什么错误?

标签: google-maps geocode


【解决方案1】:

地理编码器是异步的。您需要在回调函数中使用返回的数据,何时/何地可用。

相关问题:Using Address Instead Of Longitude And Latitude With Google Maps API

proof of concept fiddle

代码 sn-p:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-18
    • 2012-12-27
    • 2023-03-20
    • 2013-09-26
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2018-01-16
    相关资源
    最近更新 更多