根据地名定位谷歌MAP
2017-03-05 本文已影响0人
MingSha
许多时候,我们必须通过经纬度来定位地图,有没有办法通过地面直接定位。
其中的address = 'Paris, France';
即位定位到巴黎。
代码如下
<div id="map-canvas"></div>
<style type="text/css">#map-canvas {
height: 400px;
}</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Call the codeAddress function (once) when the map is idle (ready)
google.maps.event.addListenerOnce(map, 'idle', codeAddress);
}
function codeAddress() {
// Define address to center map to
var address = 'Paris, France';
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// Center map on location
map.setCenter(results[0].geometry.location);
// Add marker on location
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
initialize();
</script>