Html Google Maps API 3 搜索框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7274696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:23:41  来源:igfitidea点击:

Google Maps API 3 search box

htmlgoogle-mapssearchgoogle-maps-api-3

提问by shinjuo

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?

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

回答by Jiri Kriz

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

谷歌地图中没有针对此任务的完整“小部件”。但它很容易实现。在 HTML 中,您可以有一个文本字段和一个“搜索”按钮。(相反,您可以处理文本字段中的 Enter 键)。

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

In Javascript you instantiate and use a Geocoder:

在 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); 
            } 
        }
    );
};