要缩放地图以最好地显示地理编码操作的结果,您可以使用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>