Google Maps API 3 search box

萝らか妹 提交于 2019-12-20 09:45:15

问题


I cannot figure out how to implement the search box in my google maps. I have it where the user can pick some stuff from a form and it loads the markers on the map. Now I want to add where they can type in the city and state using the google search box, like on maps.google.com. Can this be done with API v. 3?


回答1:


There is no complete "widget" in Google maps for this task. But it is easy to accomplish it. In HTML you can have a text field and a button "Search". (Instead you can handle the Enter key in the text field).

<input type="text" id="search_address" value=""/>
<button onclick="search();">Search</button>

In Javascript you instantiate and use a Geocoder:

var addressField = document.getElementById('search_address');
var geocoder = new google.maps.Geocoder();
function search() {
    geocoder.geocode(
        {'address': addressField.value}, 
        function(results, status) { 
            if (status == google.maps.GeocoderStatus.OK) { 
                var loc = results[0].geometry.location;
                // use loc.lat(), loc.lng()
            } 
            else {
                alert("Not found: " + status); 
            } 
        }
    );
};


来源:https://stackoverflow.com/questions/7274696/google-maps-api-3-search-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!