我使用Google Maps JavaScript API和this solution获取地图上最近的点并显示它们。
" PT"值示例:
38.5803844,-121.50024189999999
以下是代码:
function findClosestN(pt,numberOfResults) {
var closest = [];
for (var i=0; i<gmarkers.length;i++) {
gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers[i].getPosition());
gmarkers[i].setMap(null);
closest.push(gmarkers[i]);
}
closest.sort(sortByDist);
return closest;
}
function sortByDist(a,b) {
return (a.distance- b.distance)
}
function calculateDistances(pt,closest,numberOfResults) {
var service = new google.maps.DistanceMatrixService();
var request = {
origins: [pt],
destinations: [],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
};
for (var i=0; i<closest.length; i++) request.destinations.push(closest[i].getPosition());
service.getDistanceMatrix(request, function (response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('search_results');
outputDiv.innerHTML = '';
var splitLoc = pt;
splitLoc.split(",");
alert(splitLoc[1]);
photo_lat = splitLoc[0]; // lat
photo_lng = splitLoc[1]; // lng
profile_photo = "https://maps.googleapis.com/maps/api/streetview?size=600x300&location=" + photo_lat + "," + photo_lng + "&heading=151.78&pitch=-0.76";
var results = response.rows[0].elements;
for (var i = 0; i < numberOfResults; i++) {
closest[i].setMap(map);
outputDiv.innerHTML += "<div class='location_list' style='background:url(" + profile_photo + ");'>" + "<div class='inner'>" + "<a href='javascript:google.maps.event.trigger(closest["+i+"],\"click\");'>"+closest[i].title + '</a><br>' + closest[i].address+"<br>"
+ results[i].distance.text + ' appoximately '
+ results[i].duration.text
+ "</div></div>";
}
}
});
}
在最后一个函数calculateDistances中,我试图从&#34; pt&#34;中分离坐标。变量然后将lat和lng传递到街景图像api中以输出每个位置的静态图像。
我收到错误:
Uncaught TypeError: splitLoc.split is not a function
试图分裂时。我的猜测是,pt的格式不正确,但我无法弄明白。当我单独警告pt时,它会将lat和lng一起显示正确,但错误发生在拆分上。
如何将pt拆分为单独的lat lng然后将其传递?
答案 0 :(得分:2)
pt不是字符串,而是具有lat和lng属性的对象。但是如果你调用alert(pt),它会将对象强制转换为字符串。
例如
pt.toString() “(37.4418834,-122.14301949999998)”
要获得lat / lng,只需使用pt.lat()或pt.lng()