gpt4 book ai didi

javascript - 谷歌地图 V3 地理编码 + 缩放

转载 作者:搜寻专家 更新时间:2023-11-01 04:44:46 24 4
gpt4 key购买 nike

我正在使用 Javascript API 的 Google map 版本 2 的地理编码服务。 https://developers.google.com/maps/documentation/javascript/v2/reference然而谷歌决定不再支持他的。

Note: The Google Maps JavaScript API Version 2 has been officially deprecated as of May 19, 2010. The V2 API will continue to work until May 19, 2013. We encourage you to migrate your code to version 3 of the Maps JavaScript API.

那么我如何在带有缩放功能的 google maps 版本 3 javascript api 中进行地理编码?

最佳答案

要缩放 map 以最好地显示地理编码操作的结果,您可以使用 google.maps.Map fitBounds方法与结果的视口(viewport)属性:

function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if (results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

代码片段:

var geocoder, map, marker;

function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if (results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(
document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addDomListener(document.getElementById('btn'), 'click', codeAddress);
codeAddress();

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="address" value="Palo Alto, CA" />
<input id="btn" value="Geocode" type="button" />
<div id="map_canvas"></div>

关于javascript - 谷歌地图 V3 地理编码 + 缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13689270/

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