我正在使用Google Maps Version 2的地理编码服务Javascript API。 https://developers.google.com/maps/documentation/javascript/v2/reference 然而谷歌决定不再支持他了。
注意:Google Maps JavaScript API第2版已正式发布 自2010年5月19日起弃用.V2 API将继续有效,直到 2013年5月19日。我们建议您将代码迁移到版本3 Maps JavaScript API。
那么如何在谷歌地图版本3 javascript api中使用缩放进行地理编码?
答案 0 :(得分:21)
要缩放地图以最好地显示地理编码操作的结果,您可以将google.maps.Map fitBounds方法与结果的视口属性一起使用:
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>
答案 1 :(得分:1)
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': zipcode }, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
map.setZoom(12);
}
else
{
alert(zipcode + " not found");
console.log("status : ", status);
}
});