Javascript 谷歌地图API:强制放大到特定位置
我对GoogleMapsAPI还很陌生,我想知道是否有办法强制放大到一个特定的位置,例如:美国 我要寻找的是一种模拟鼠标滚轮放大效果的方法,如果光标在美国,当你用滚轮放大时,中心将开始向光标移动 我尝试使用“zoom_changed”事件并动态更改中心,但由于它没有在桌面(设备模式)下运行,因此该事件仅在末尾触发() 这是我的密码:Javascript 谷歌地图API:强制放大到特定位置,javascript,google-maps,Javascript,Google Maps,我对GoogleMapsAPI还很陌生,我想知道是否有办法强制放大到一个特定的位置,例如:美国 我要寻找的是一种模拟鼠标滚轮放大效果的方法,如果光标在美国,当你用滚轮放大时,中心将开始向光标移动 我尝试使用“zoom_changed”事件并动态更改中心,但由于它没有在桌面(设备模式)下运行,因此该事件仅在末尾触发() 这是我的密码: var map; var centerUS; var currentCenter; var currentZoom; function initMap() {
var map;
var centerUS;
var currentCenter;
var currentZoom;
function initMap() {
//define Map
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 0, lng: 0},
zoom: 3,
disableDefaultUI: true
});
//limit the zoom
map.setOptions({ minZoom: 3, maxZoom: 10 });
//initialization of variables
currentZoom = map.getZoom();
currentCenter = map.getCenter();
centerUS = new google.maps.LatLng(40, -100);
//add the listener for zooming in
map.addListener('zoom_changed', function () {
zoomInTheUS();
});
}
function zoomInTheUS() {
//get new values
var newZoom = map.getZoom();
currentCenter = map.getCenter();
//if the user is zooming in
if (newZoom > currentZoom) {
//difference between the current center and the center of the US
var changeLat = centerUS.lat() - currentCenter.lat();
var changeLng = centerUS.lng() - currentCenter.lng();
//approach the center of the US by a factor of 10% of the distance
var newLat = currentCenter.lat() + changeLat * 0.1;
var newLng = currentCenter.lng() + changeLng * 0.1;
//define new center and pan to it
var newCenter = new google.maps.LatLng(newLat, newLng);
map.panTo(newCenter);
}
//actualize the value of currentZoom
currentZoom = newZoom;
}
我试图在“拖动”事件期间执行此操作,因为它会反复触发,但不起作用。我认为这可能是因为事件触发得非常快,newZoom和currentZoom变量几乎总是具有相同的值。或者,在设备模式下,Google Maps API中的缩放变量会在事件结束时刷新。我只是假设,我不知道
有没有办法实现我想要的?我曾想过在检测到两个手指时禁用平移,或者可能从设备模式更改为非设备模式,但我没有找到任何相关信息
提前谢谢。您可以先尝试定位自己的位置,然后自动缩放到该位置 我在这里举了一个示例,说明如何放大要放大的位置:
函数getPlaces(查询){
服务=新建google.maps.places.PlacesService(
document.getElementById('attributes')//attributes容器
);
//发送查询
textSearch({query:query},函数(结果,状态){
if(status==google.maps.places.PlacesServiceStatus.OK){
对于(var i=0;i
#地图{
身高:100%;
}
html,正文{
身高:100%;
保证金:0;
填充:0;
}
当有属性时,您将在此处看到属性
var starttatlng,//将其更改为接近映射结束位置的某个值
allMarkers=[],//保留标记的全局副本
mapPointsBounds=[],//映射所有标记的边界
地图//地图副本
//谷歌会在准备好后调用它,它是`&callback=initMap`上面脚本标记中的一个查询字符串:
函数initMap(查询){
starttatlng=newgoogle.maps.LatLng([0,0]);
mapPointsBounds=新的google.maps.LatLngBounds();
map=new google.maps.map(document.getElementById('map'){
中心:惊人,
缩放:13
});
getPlaces(查询);
}
您可以省去麻烦,只提供美国的瓷砖,这样即使用户想看美国以外的地方,也不能看。如果有帮助,请查看我的答案,如果没有帮助,请发布您自己的答案。