【问题标题】:Google maps API geocoding - Cannot read property of nullGoogle 地图 API 地理编码 - 无法读取 null 的属性
【发布时间】:2016-11-17 11:01:22
【问题描述】:

我的 google api 代码有问题。问题是我在引导模式中使用了地理编码,当我填充输入时第一次单击时,我在控制台中有信息:无法读取 null 的属性。这是我的代码示例:

var location1;
var location2;
function licz() {
        var geocoder = new google.maps.Geocoder();

        if (geocoder) {
            geocoder.geocode({ 'address': document.getElementById('txtMiasto1').value }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    location1 = results[0].geometry.location;
                    console.log(location1);

                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
            geocoder.geocode({ 'address': document.getElementById('txtMiasto2').value }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    location2 = results[0].geometry.location;
                    console.log(location2);

                } else {
                    alert("Geocode was not successful for the following reason: " + status);

            latlng = new google.maps.LatLng((location1.lat() + location2.lat()) / 2, (location1.lng() + location2.lng()) / 2);



            var mapOptions = {
                center: latlng,
                zoom: 15,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

            directionsService = new google.maps.DirectionsService();
            directionsDisplay = new google.maps.DirectionsRenderer(
            {
                suppressMarkers: true,
                suppressInfoWindows: true
            });
            directionsDisplay.setMap(map);
            var request = {
                origin: location1,
                destination: location2,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                    distance = response.routes[0].legs[0].distance.text;
                    document.getElementById("txtDistance").value = distance;
                }
            });

            var marker1 = new google.maps.Marker({
                map: map,
                position: location1,
                title: "Start"
            });

            var marker2 = new google.maps.Marker({
                map: map,
                position: location2,
                title: "Koniec"
            });

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

        if (geocoder) {
            geocoder.geocode({ 'address': document.getElementById('txtMiasto1').value }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    location1 = results[0].geometry.location;
                    console.log(location1);

                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
            geocoder.geocode({ 'address': document.getElementById('txtMiasto2').value }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    location2 = results[0].geometry.location;
                    console.log(location2);

                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });

        }

函数 licz() 在模态按钮中的 OnClick 处理如下:

<button type="button" runat="server" id="btnLicz" class="btn btn-info" onclick="licz();">Calculate</button>

当我再次点击时,问题解决了。

有人能告诉我我做错了什么吗?

感谢您的帮助!

【问题讨论】:

  • 这个错误是在哪里抛出的?
  • 当我第一次单击按钮时,错误消息是“location1 未定义”或“location1 无法读取 null 属性”对不起,我现在不在我的电脑上
  • 目前还不清楚,因为您的代码中有很多对 location1 的引用。当您返回计算机时,请提供代码中引发错误的确切行。
  • in line ' latlng = new google.maps.LatLng((location1.lat() + location2.lat()) / 2, (location1.lng() + location2.lng()) / 2); '

标签: javascript jquery google-maps google-geocoder


【解决方案1】:

geocoder.geocode() 调用是异步的。这意味着当你打电话时:

latlng = new google.maps.LatLng((location1.lat() + location2.lat()) / 2, (location1.lng() + location2.lng()) / 2);

location1 尚未定义。

为避免这种情况,您必须构建如下内容:

geocoder.geocode({ 'address': document.getElementById('txtMiasto1').value }, function (results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    location1 = results[0].geometry.location;
    geocoder.geocode({ 'address': document.getElementById('txtMiasto2').value }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        location2 = results[0].geometry.location;
        latlng = new google.maps.LatLng((location1.lat() + location2.lat()) / 2, (location1.lng() + location2.lng()) / 2);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  } else {
    alert("Geocode was not successful for the following reason: " + status);
  }
});

但是有更优雅的方式来处理这种情况,比如 Promise(es6 特性,但存在库):

var location1;
var location2;

function geocode(data){
  return new Promise((resolve,reject)=>{
    geocoder.geocode(data, (results, status) => {
      if (status == google.maps.GeocoderStatus.OK) 
        resolve(results[0].geometry.location);
      else
        reject();
    });
  })
}
var asyncs=[
  geocode({ 'address': document.getElementById('txtMiasto1').value }).then(result=>location1=result),
  geocode({ 'address': document.getElementById('txtMiasto2').value }).then(result=>location2=result)
]
Promise.all(asyncs).then(()=>{
  //do stuffs with location1 and location2
}).catch(()=>{
  //handle errors
})

请注意,此代码适用于现代浏览器(支持箭头函数和 Promises,如 Chrome 和 Firefox),但您可以用普通的旧 function(){} 替换箭头函数并使用类似 this one 的 Promise 库(首先谷歌结果,从未测试过)

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2020-08-08
    相关资源
    最近更新 更多