Google Maps API 3搜索框

shi*_*juo 7 html search google-maps google-maps-api-3

我无法弄清楚如何在我的谷歌地图中实现搜索框.我有它,用户可以从表单中选择一些东西,并在地图上加载标记.现在,我想添加他们可以使用谷歌搜索框在城市和州中输入的内容,例如maps.google.com.这可以通过API v.3完成吗?

Jir*_*riz 26

Google地图中没有完整的"小部件"来执行此任务.但它很容易实现.在HTML中,您可以有一个文本字段和一个"搜索"按钮.(相反,您可以在文本字段中处理Enter键).

<input type="text" id="search_address" value=""/>
<button onclick="search();">Search</button>
Run Code Online (Sandbox Code Playgroud)

在Javascript中,您实例化并使用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); 
            } 
        }
    );
};
Run Code Online (Sandbox Code Playgroud)