未定义地理编码中的变量,如何正确调用它们

Variables from geocoding not defined, how to call them correctly?

本文关键字:何正确 调用 变量 编码 未定义      更新时间:2023-09-26

我正在尝试学习javascript并使用Google Maps API,似乎我陷入了一个(希望)简单的问题。

我编写了此函数来获取地理编码坐标:

function codeAddress() {
    var st = document.getElementById('start').value;
    var dest = document.getElementById('end').value;
geocoder.geocode( { 'address': st}, function(results, status) {
 var startCoded = results[0].geometry.location;
    var startLng = results[0].geometry.location.lng();
    var startLat = results[0].geometry.location.lat();   
 document.getElementById("content1").value = startCoded;
});
    geocoder.geocode( { 'address': dest}, function(results, status) {
    var endCoded = results[0].geometry.location;
    var endLng = results[0].geometry.location.lng();
    var endLat = results[0].geometry.location.lat();        
    document.getElementById("content2").value = endCoded;
        if (status == google.maps.GeocoderStatus.OK) {
var lngSpan = startLng - endLat;  
var latSpan = startLat - endLng;
console.log(endCoded);
  }
});
    }

但是我收到此错误: 引用错误: 未定义启动Lng

我知道这与我需要回调来阅读它们的事实有关,但我不知道该怎么做。

提前谢谢。

我认为这就是您声明变量的方式(它们是函数的本地而不是全局的)。尝试:

var startLng, startLat, endLng, endLat;
function codeAddress() {
    var st = document.getElementById('start').value;
    var dest = document.getElementById('end').value;
geocoder.geocode( { 'address': st}, function(results, status) {
 var startCoded = results[0].geometry.location;
    startLng = results[0].geometry.location.lng();
    startLat = results[0].geometry.location.lat();   
 document.getElementById("content1").value = startCoded;
});
    geocoder.geocode( { 'address': dest}, function(results, status) {
    var endCoded = results[0].geometry.location;
    endLng = results[0].geometry.location.lng();
    endLat = results[0].geometry.location.lat();        
    document.getElementById("content2").value = endCoded;
        if (status == google.maps.GeocoderStatus.OK) {
var lngSpan = startLng - endLat;  
var latSpan = startLat - endLng;
console.log(endCoded);
  }
});
    }