gpt4 book ai didi

javascript - 从 Google API 位置获取标记总数搜索

转载 作者:行者123 更新时间:2023-11-28 19:47:16 25 4
gpt4 key购买 nike

在示例 fiddle 中,如何获取 map 上显示的标记总数?我将每个标记插入一个数组,如下所示:

markers.push(marker)

并尝试获取这样的标记总数:

$('.marker-count span').html(markers.length);

不幸的是,“markers.length”在应该至少返回 3 的情况下却返回 0。我这里有示例代码:http://jsfiddle.net/287C7/

如何显示标记总数?是否无法将每个标记添加到我的数组中?

我需要知道显示的标记数量,以便在没有标记时提醒用户。

谢谢

如果您不想在 jsfiddle.net 上查看代码,这里是:

    var map, places, tmpLatLng, markers = [];

var pos = new google.maps.LatLng(51.5033630,-0.1276250);
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(51.5033630,-0.1276250)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// create the map and reference the div#map-canvas container
var markerBounds = new google.maps.LatLngBounds();
var service = new google.maps.places.PlacesService(map);


// fetch the existing places (ajax)
// and put them on the map

var request = {
location: pos,
radius: 48000, // Max radius
name: "mc donalds"
};
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
$('#map-canvas').attr("data-markers",results.length);
$('.marker-count span').html(markers.length);
} else {
console.log("Places request failed: "+status);
}
} // end callback
function createMarker(place) {
var prequest = {
reference: place.reference
};
var tmpLatLng = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
markers.push(marker);
markerBounds.extend( tmpLatLng );
} // end createMarker
service.nearbySearch(request, callback);

最佳答案

当您运行代码时,placesSearch 调用是异步的:

$('.marker-count span').html(markers.length);

结果还没有从服务器返回。您需要在更新标记数组后的回调中执行此操作。

        function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
$('#map-canvas').attr("data-markers",results.length);
$('.marker-count span').html(markers.length);
} else {
console.log("Places request failed: "+status);
}
} // end callback

working fiddle

关于javascript - 从 Google API 位置获取标记总数搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24070293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com