如何将地点搜索框添加到地图?

时间:2014-02-11 08:55:18

标签: javascript api google-maps maps

我有兴趣在我的Google地图中实施Google地图搜索框。如何在此地图代码中添加地点搜索框:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map_canvas" style="width: 700px; height: 600px; float: left; margin: 10px"></div>
<script type="text/javascript">
    function InitializeMap() {
        var latlng = new google.maps.LatLng(32, 35);
        var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP };

        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }
    window.onload = InitializeMap;
</script>

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
        <script>
            var geocoder;
            var map;
           function InitializeMap() {

                geocoder = new google.maps.Geocoder();
               var latlng = new google.maps.LatLng(32, 35);

               var myOptions = {

                   zoom: 8,

                   center: latlng,

                   mapTypeId: google.maps.MapTypeId.ROADMAP

               };

               map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

           }

           function searchAddress() {

               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);
                               document.getElementById('address').value = results[0].formatted_address;
                           }
                       }
               );
           }

           //window.onload = InitializeMap;
           google.maps.event.addDomListener(window, 'load', InitializeMap);
        </script>
    </head>
    <body>
        <div>
            <input id="address" type="text" name="address" value="">
            <input type="button" value="Search" onclick="searchAddress()">
        </div>
        <div id="map_canvas" style="width:400px; height:400px;"></div>
    </body>
</html>