Javascript 谷歌地图获取具有城市名称的纬度和经度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11149144/
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-24 04:41:07  来源:igfitidea点击:

Google maps get latitude and longitude having city name?

javascriptgoogle-maps

提问by lisovaccaro

I want to get latitude and longitude of a city by providing the API with the city name. It should work for most cities regardless how the user inputs the city.

我想通过为 API 提供城市名称来获取城市的纬度和经度。无论用户如何输入城市,它都应该适用于大多数城市。

For example:

例如:

City can be 'miami, US' or city can be 'miami, united states'

城市可以是“迈阿密,美国”或城市可以是“迈阿密,美国”

How do I print its latitude?

我如何打印它的纬度?

回答by Zakaria

You can find the code jsfiddled here : http://jsfiddle.net/YphZw/or below :

您可以在此处找到 jsfiddled 代码:http: //jsfiddle.net/YphZw/或以下:

$("#btn").click(function(){
            var geocoder =  new google.maps.Geocoder();
    geocoder.geocode( { 'address': 'miami, us'}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng()); 
          } else {
            alert("Something got wrong " + status);
          }
        });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body>
    <input id="btn" type="button" value="search for miami coordinates" />
</body>
</html>

If you want more examples for the Javascript API, try this link : https://developers.google.com/maps/documentation/javascript/examples/

如果您想要更多 Javascript API 示例,请尝试此链接:https: //developers.google.com/maps/documentation/javascript/examples/

The code I wrote is inspired from the geocoding-simplesample.

我编写的代码灵感来自地理编码简单示例。

Regards.

问候。

EDIT 1:

编辑 1:

You can achieve it using an non-official PHP library. Check this example : http://www.bradwedell.com/phpgooglemapapi/demos/geocoding.php(The code is at the bottom=

您可以使用非官方 PHP 库来实现它。检查这个例子:http: //www.bradwedell.com/phpgooglemapapi/demos/geocoding.php(代码在底部=

回答by debracey

You can use Google's geocoding service, e.g.,

您可以使用 Google 的地理编码服务,例如,

http://maps.googleapis.com/maps/api/geocode/xml?address=Miami+FL&sensor=false

http://maps.googleapis.com/maps/api/geocode/xml?address=Miami+FL&sensor=false

That gives you back georeferenced data in a variety of formats (JSON, XML, etc). In any event, the location is definitely in the returned data block.

这为您提供了各种格式(JSON、XML 等)的地理参考数据。无论如何,该位置肯定在返回的数据块中。

The API docs are at:

API 文档位于:

https://developers.google.com/maps/documentation/geocoding/

https://developers.google.com/maps/documentation/geocoding/

回答by corysimmons

Update per comment below:Doesn't work after July 2018.

根据以下评论更新:2018 年 7 月后不起作用。



This seems needlessly complicated. Here's an example "nearby events" map. It will take City, States, convert them to latLngcoords, and put markers on a map:

这似乎不必要地复杂。这是“附近事件”地图的示例。这将需要City, States,将它们转换为latLng坐标,然后在地图上放置标记:

// Nearby Events with Google Maps
window.nearbyEventsMap = () => {
    const centerOfUS = {
        lat: 37.09024,
        lng: -95.712891
    }

    // Create a map object and specify the DOM element for display.
    const map = new google.maps.Map(document.querySelector('#nearby_events_map'), {
        center: centerOfUS,
        scrollwheel: false,
        zoom: 4
    })

    // Create a marker and set its position.
    const geocoder = new google.maps.Geocoder()

    // Filter out duplicate cityStates
    let cityStates = {}
    document.querySelectorAll('.nearby_event_city_state').forEach(event => {
        cityStates[event] = event.innerText
    })

    // `cityState` is in the format of "City, State". It's not picky about state being a word or the abbreviation.
    for (const cityState in cityStates) {
        const location = cityStates[cityState]

        geocoder.geocode({
            address: location
        }, function (results, status) {
            if (status === 'OK') {
                const result = results[0].geometry.location
                const lat = result.lat()
                const lng = result.lng()
                const latLng = {
                    lat,
                    lng
                }

                return new google.maps.Marker({
                    map: map,
                    position: latLng
                })
            }
        })
    }
}
// /Nearby Events with Google Maps

Make sure to include your <script>tags.

确保包含您的<script>标签。

<script src="/dist/js/main.js"></script>

<!-- We're loading this after the main.js script so the callback from main.js will be available to it. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=nearbyEventsMap"></script>

StackOverflow please join everyone else and get GitHub markdown with syntax highlighting...

StackOverflow 请加入其他所有人,并通过语法高亮显示 GitHub 降价...