Google Javascript API调用以及Geolocator代码不起作用

Google Javascript API call along with Geolocator code doesnt work

本文关键字:Geolocator 代码 不起作用 Javascript API 调用 Google      更新时间:2023-09-26

我试图将纬度和经度的值视为全局变量,以便可以使用它。但是,当调用 codeAddress(( 函数时,甚至在它完成执行之前,也会打印后续的内部警报,并且 map 呈现为空白(代码显示硬编码值(。我做错了什么?

var geocoder;
    var geoloc;
    var latitude;
    var longitude
function codeAddress() {
     geocoder = new google.maps.Geocoder();
    var address = 'Dallas';
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        latitude = results[0].geometry.location.lat();alert(latitude);
        longitude = results[0].geometry.location.lng();alert(longitude);
    } else {
      alert('Geocode was not successful for the following the default location set.reason: ' + status);
    }
  });
    return;
}
function getStoreMap(zoom)
{
codeAddress();
google.maps.event.addDomListener(window, 'load', function() {
    alert("Inside"+latitude);
    var map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: new google.maps.LatLng(32.7801399,-96.80045109999998),
    zoom: zoom,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var panelDiv = document.getElementById('panel');
  var data = new PlacesDataSource(map);
  var view = new storeLocator.View(map, data,{ updateOnPan: true}
);
  var markerSize = new google.maps.Size(24, 24);
  view.createMarker = function(store) {
    return new google.maps.Marker({
      position: store.getLocation(),
      icon: new google.maps.MarkerImage(store.getDetails().icon, null, null,
          null, markerSize)
    });
  };
  new storeLocator.Panel(panelDiv, {
    view: view
  });
});
}

对 Google API 的调用是异步的,因此当您调用 codeAddress(( 时,它开始调用可以继续处理其余代码。

然后添加文档加载,并在加载文档时调用警报。

加载文档时,对 Google 的调用尚未完成,并且未及时分配经度变量。

在加载时设置文档以初始化地图并调用地理定位。在地理定位调用的函数完成时,调用另一个函数将根据结果修改地图。