首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Javascript中从lat/long获取城市名称

在Javascript中从lat/long获取城市名称
EN

Stack Overflow用户
提问于 2018-09-04 16:36:22
回答 1查看 35关注 0票数 0

我可以从以下代码中检索经度/经度。根据这个值,我应该能够获得城市名称。

代码语言:javascript
复制
    <!DOCTYPE html>
    <html>
    <body>

    <p>Click the button to get your coordinates.</p>

    <button onclick="getLocation()">Try It</button>

    <p id="demo"></p>

    <script>
    var x = document.getElementById("demo");

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else { 
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

    function showPosition(position) {

        x.innerHTML = "Latitude: " + position.coords.latitude + 
        "<br>Longitude: " + position.coords.longitude;


        var geocoder;
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

        geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var add= results[0].formatted_address ;
                    var  value=add.split(",");

                    count=value.length;
                    country=value[count-1];
                    state=value[count-2];
                    city=value[count-3];
                    alert("city name is: " + city);
                }
                else  {
                    alert("address not found");
                }
        }
         else {
            alert("Geocoder failed due to: " + status);
        }
    }

    </script>

    </body>
    </html>

我从一些文章中读到了Geo-location API。我不确定这是不是真的需要,因为我没有在这里实现地图。我只需要现在所在城市的名字

EN

回答 1

Stack Overflow用户

发布于 2018-09-04 16:49:33

这取决于你的目的。如果您想在小范围内使用此应用程序,最好在数据库中硬编码城市名称和经度/纬度,然后可以获取当前的经度/纬度,并检查数据库中的匹配项以获得一定的准确率。这取决于你的需要。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52162131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档