输入框中的地理编码位置

时间:2012-05-21 02:20:28

标签: javascript google-maps geocode

我是谷歌地图的新手,只是试图抓住它。我希望能够输入城市或地址,然后让地图加载并放置标记。

现在我的地图最初加载正常,但是当我输入城市或地址时没有任何反应。知道这里发生了什么吗?

<script type="text/javascript">
var geocoder;
var map;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlang = new google.maps.LatLng(42, -84);
    var myOptions = {
        center: latlang, zoom: 5, mapTypeId: google.maps.MapTypeId.SATELLITE,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.SMALL
        }
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
  }

  function codeAddress() { 
    var sAddress = document.getElementById("newLocation").value;
    geocoder.geocode( { 'address': sAddress}, 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);
            }
        });
  }
</script>
</head>
  <body onload="initialize()">
    Address: <input type="text" id="newLocation" style=" width:200px" title="Address to Geocode" />     
    <input type="button" onclick="codeAddress()" id="inputButtonGeocode" style="width:150px" title="Click to Geocode" value="Geocode" />
    <div id="map_canvas" style="width:100%; height:100%"></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:4)

在第

var map = new google.maps.Map(document.getElementById("map_canvas")...

删除单词var。因为它在功能局部范围内创建map,并且地理编码功能仅查看先前(空)map变量。通过删除它,全局map变量将更新为此新的Google地图。