【问题标题】:How to add places search box to a map?如何将地点搜索框添加到地图?
【发布时间】:2014-02-11 08:55:18
【问题描述】:

我有兴趣在我的谷歌地图中实现一个谷歌地图搜索框。如何在此地图代码中添加地点搜索框:

<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>

【问题讨论】:

    标签: javascript api google-maps maps


    【解决方案1】:

    【讨论】:

    • 请帮我在上面的代码中添加标记和自动完成功能。最好!
    【解决方案2】:
    <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>
    

    【讨论】:

    • 您还可以在地图上添加标记(默认在 InitializeMap() 中并在 searchAddress() 中选择)
    • 谢谢你,Alex,你能帮我标记一下吗?
    猜你喜欢
    • 1970-01-01
    • 2014-02-20
    • 2012-10-28
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    相关资源
    最近更新 更多