在谷歌地图中使用地址查找位置

时间:2015-06-12 10:42:21

标签: javascript google-maps

是否可以使用该地点的地址和邮政编码在谷歌地图中获取确切位置?如果没有,建议我解决这个问题的其他方法。我搜索了很多,但我不知道该怎么做。

提前致谢......

2 个答案:

答案 0 :(得分:2)

您可以使用Google地图的反向地理编码(地址查询) https://developers.google.com/maps/documentation/javascript/geocoding

答案 1 :(得分:2)

以下是代码。只需添加位置并单击地理编码按钮。

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Geocoding service</title>
<style>
  html, body{
    margin: 0px;
    padding: 0px;
  }
  #panel {
    position: absolute;
    top: 5px;
    left: 50%;
    margin-left: -180px;
    z-index: 5;
    background-color: #fff;
    padding: 5px;
    border: 1px solid #999;
  }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 13,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {
document.getElementById("dis").setAttribute('style','visibility:visible;');
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
    });
} else {
  alert('Geocode was not successful for the following reason: ' + status);
}
 });
}

google.maps.event.addDomListener(window, 'load', initialize);

</script>
<style type="text/css">
.display{visibility:hidden ;width: 700px;height: 400px;position: fixed;top: 0;left: 0;right: 0;bottom: 0;margin: auto;}
</style>
 </head>
 <body>
<div id="panel">
  <input id="address" type="textbox" value="Pathankot">
  <input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div class="display" id="dis">
<div id="map-canvas" style="width:400px;height:400px"></div>
</div>
</body>
</html>