2012-12-03 139 views
3

我使用的是Google地圖版本2的地理編碼服務JavaScript API。 https://developers.google.com/maps/documentation/javascript/v2/reference 但谷歌決定不再支持他了。谷歌地圖V3地理編碼+縮放

注:谷歌地圖的JavaScript API第2版已正式 棄用2010年5月19日的V2 API將繼續下去,直到 工作2013年5月19日,我們建議您將自己的代碼遷移到版本3的 Maps JavaScript API。

那麼我怎樣才能在谷歌地圖版本3 javascript api縮放地理編碼?

回答

19

縮小地圖,以最好的表演地理編碼操作的結果,你可以使用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); 
    } 
});