如何从坐标获取城市? [英] How to get city from coordinates?

查看:317
本文介绍了如何从坐标获取城市?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用google maps api 3从坐标获取城市。
我阅读了ReverseGeocoding,但我不明白如何从此类结果中获得正确的城市值:
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false

I use google maps api 3 to get city from coordinates. I read the ReverseGeocoding but I did not understand how to have the correct city value from this type of result: http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false

推荐答案

此Funktion以纬度/经度返回所请求城市的名称。因为这个脚本是从2012年底开始的。那次对我来说工作得很好。当API找不到时返回未知。

this Funktion returns the Name of a requested City at lat/long. As this Script is from end of 2012. Worked fine for me that time. Returns "unknown" when the API doesn't find any.

function get_api ($lat, $long) {
    $get_API = "http://maps.googleapis.com/maps/api/geocode/json?latlng=";
    $get_API .= round($lat,2).",";
    $get_API .= round($long,2);         

    $jsonfile = file_get_contents($get_API.'&sensor=false');
    $jsonarray = json_decode($jsonfile);        

    if (isset($jsonarray->results[1]->address_components[1]->long_name)) {
        return($jsonarray->results[1]->address_components[1]->long_name);
    }
    else {
        return('Unknown');
    }
}

编辑:和一个jquery。

edit: and a jquery.

<p id="city"></p>

<script>
$(document).ready( function () {    
    // define lat / long
    var lat = 37.42;
    var long = -122.08;

    $.ajax({
        type: 'GET',
        dataType: "json",
        url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&sensor=false",
        data: {},
        success: function(data) {
            $('#city').html(data);
            $.each( data['results'],function(i, val) {
                $.each( val['address_components'],function(i, val) {
                    if (val['types'] == "locality,political") {
                        if (val['long_name']!="") {
                            $('#city').html(val['long_name']);
                        }
                        else {
                            $('#city').html("unknown");
                        }
                        console.log(i+", " + val['long_name']);
                        console.log(i+", " + val['types']);
                    }
                });
            });
            console.log('Success');
        },
        error: function () { console.log('error'); } 
    }); 
});
</script>

这篇关于如何从坐标获取城市?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆