我正在尝试使用API中的信息构建地图。不幸的是,数据集没有坐标。所以我使用地址并对它们进行地理编码以构建带有标记的谷歌地图,并从当前位置获取距离以及方向。我获取用户的当前位置,并找到周围10英里半径的请求信息。
这是我的地理编码功能
<script>
var geocoder = new google.maps.Geocoder();
function geocodeAddress(geocoder, street, city, zip) {
var address = street + ', ' + city + ', ' + zip;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
console.log(results[0].geometry.location.lat(), results[0].geometry.location.lng());
debugger;
return(results[0].geometry.location.lat(), results[0].geometry.location.lng());
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
以下是扫描API调用中所有数据的循环
$my_counter = 0;
foreach ($param as &$value){
$row = $value;
echo"
<script>
//the return information is messy so i use this to clean it up
var coordinates = geocodeAddress(geocoder, '".trim(str_replace(',', '',$row->address))."', '".trim($row->city)."', '".trim($row->zip)."');
console.log(coordinates);
var new_lat = parseFloat(coordinates[0]);
var new_long = parseFloat(coordinates[1]);
var distance_to_the_point = haversineGreatCircleDistance (".$original_gps_lat.", ".$original_gps_long.", new_lat, new_long);
if (distance_to_the_point <= ".$radius."){
var data = '".$row->phone."';
var result = data;
var rounded_distance = distance_to_the_point.toFixed(2);
var name = '".trim($row->provider_name)."';
document.getElementById('name').innerHTML = name.toString();
}
";
</script>
现在,当我使用断点和日志运行时,我看到地理编码功能正在运行,但从未给出返回。然后一旦页面加载,地理编码器就完成了,我看到了返回的坐标。我不明白为什么它没有同步运行。