gpt4 book ai didi

javascript - 从坐标数组中,我如何决定将 map 居中?

转载 作者:行者123 更新时间:2023-11-30 08:07:47 25 4
gpt4 key购买 nike

假设我正在使用以下位置的 JSON:

var beaches = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];

我在 Google map 上绘制这些,我想大致以中间的那个为中心。

Google map API 中是否有执行此操作的函数?还是我必须自己算出平均值?

我已经编写了一个函数,我可以将 JSON 和缩放级别传递给:

function initialize_map(places, zoom) {

// use first coordinates in the json to initiate the map
var place_lat_lng = new google.maps.LatLng(places[0][1],places[0][2]);

var mapOptions = {
zoom: zoom,
center: place_lat_lng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);

var marker, i;

// loop through all the places to get markers
for (var i=0;i<places.length;i++)
{
var place = places[i];

marker = new google.maps.Marker({
position: new google.maps.LatLng(place[1], place[2]),
map: map,
animation: google.maps.Animation.DROP
});
// add the marker
marker.setMap(map);
}
}

此功能有效,但它不会居中,并且标记会在 View 之外。

您将如何使 View 居中并使所有标记都可见?

最佳答案

Google Maps API v3 contains a method for displaying a set of markers :

fitBounds(bounds:LatLngBounds) - None - Sets the viewport to contain the given bounds.

将所有标记添加到 google.maps.LatLngBounds 对象,然后在 map 对象上调用该方法。像这样:

function initialize_map(places, zoom) {
var bounds = new google.maps.LatLngBounds(); // empty bounds object

// use first coordinates in the json to initiate the map
var place_lat_lng = new google.maps.LatLng(places[0][1],places[0][2]);

var mapOptions = {
zoom: zoom,
center: place_lat_lng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);

var marker, i;

// loop through all the places to get markers
for (var i=0;i<places.length;i++)
{
var place = places[i];

marker = new google.maps.Marker({
position: new google.maps.LatLng(place[1], place[2]),
map: map,
animation: google.maps.Animation.DROP
});
// add the marker
marker.setMap(map);
bounds.extend(marker.getPosition()); // add the marker to the bounds

}

map.fitBounds(bounds); // show all the markers.
}

关于javascript - 从坐标数组中,我如何决定将 map 居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15158252/

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