javascript - 谷歌地图 API : forcing zoom in to a specific location

标签 javascript google-maps

我对 Google Maps API 还很陌生,我想知道是否有办法强制放大到特定位置,例如:美国。

我正在寻找的是一种模拟鼠标滚轮放大效果的方法,如果光标在美国,当你用滚轮放大时,中心将开始向光标。

我尝试使用“zoom_changed”事件并动态更改中心,但由于它不是在桌面(设备模式)中运行,因此该事件仅在结束时触发( source )。

这是我的代码:

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 中的缩放变量可能会在事件结束时刷新。我只是假设,我不知道。

有办法实现我想要的吗?我想过在检测到 2 个手指时禁用平移,或者可能从设备模式更改为非设备模式,但我还没有找到任何相关信息。

提前谢谢您。

最佳答案

您可以先尝试找到自己的位置,然后自动缩放到该位置。 https://stackoverflow.com/a/20930874/7707749

我在这里举了一个如何放大您想要放大的位置的示例:

function getPlaces(query) {
	service = new google.maps.places.PlacesService(
	  document.getElementById('attributions') //attributions-container
	);

	//send a query
	service.textSearch({query:query}, function(results, status) {
		if (status == google.maps.places.PlacesServiceStatus.OK) {
			for (var i = 0; i < results.length; i++) {
        
				addMapMarker(results[i], i);
			}
			
			map.fitBounds(mapPointsBounds);
		}
	});
}


function addMapMarker(markerInfo, i) {

	var infowindow = new google.maps.InfoWindow(), marker;
	var service = new google.maps.places.PlacesService(map);
	
	var marker;
	
	//this is where the marker is created with position and animation
	marker = new google.maps.Marker({
		animation: google.maps.Animation.DROP,
		position:  markerInfo.geometry.location,
		map: map,
            markerInfo: markerInfo
	});
	
	allMarkers.push(marker); //keeping all markers in an array    
	mapPointsBounds.extend(markerInfo.geometry.location); //extend bounds to contain this marker
	
	google.maps.event.addListener(marker, 'click', (function(marker, i) {
		return function() {
			infowindow.setContent('<div>This is marker:' + marker + '</div>');
			infowindow.open(map, marker);
		}
	})(marker, i));
}
#map {
	height: 100%;
}

html, body {
	height: 100%;
	margin: 0;
	padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<img src="http://developers.google.com/places/documentation/images/powered-by-google-on-white.png"/>

<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" onchange="initMap(this.value)"/>  
		
<ul id="results"></ul>

<div id="attributions" style="background:#f1f1f1"> You'll see here the attributions when there are any </div>
		
<div id="map"></div>


<script src="https://maps.googleapis.com/maps/api/js?&libraries=places" async defer></script>
<script>
    var startLatLng, //change this to some value near to where the map will end up
	allMarkers = [], //keep a global copy of your markers
	mapPointsBounds = [], //map bounds of all markers
	map; //copy of the map

	//Google will call this when it's ready, it's a query string in the script tag above `&callback=initMap`:
    function initMap(query) {
        startLatLng = new google.maps.LatLng([0, 0]);
	mapPointsBounds = new google.maps.LatLngBounds();

	map = new google.maps.Map(document.getElementById('map'), {
        center: startLatLng,
		zoom: 13
	});
				
	getPlaces(query);
    }
</script>

关于javascript - 谷歌地图 API : forcing zoom in to a specific location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43274431/

相关文章:

javascript - 无法将从 Blender 导出的对象加载到 Three.js 中?

javascript - localStorage突然坏了

javascript - 具有多个字段的 AngularJS ng-options

javascript - Node 上的 gifencoder 抛出 TypeError

Android - 谷歌地图清除缓存

javascript - 某些事件未触发

javascript - 将对象数组插入 MongoDB

javascript - 谷歌地图(v3)信息窗口一直在同一个标​​记上打开

javascript - Google map 上的文本框值更改更新标记

javascript - 如何在 JavaScript 中从 json 中获取特定数据?