开发者

Fetching geo data from google API while creating new record on DB

I have an entity that one of it's members is the actual city, country that it was "created" - the user only gives me lat, long coordinates and I need to use the google API to reverse geocode the coordinates into city, country.

My question - What is the best way to fetch that 开发者_如何转开发information? is it safe enough to use a 3rd party web service in the middle of a record creating process? What are the common ways to do that?


It's certainly safe enough. The only issue is response time (as you will be calling the remote web service synchronously), but if you're doing this once only on each insert I don't think that would be much of a problem.

The Google Geocoding API will return results in XML format, so you just need to call the web service URL and pull the information you need from the response.

Here's an example reverse geocoding result:

http://maps.googleapis.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false

You don't say which language you're using, but I'm assuming PHP—here's a very basic example of parsing the response and displaying the addresses using SimpleXML:

$lat = 40.714224;
$lng = -73.961452;

$xml = simplexml_load_file("http://maps.googleapis.com/maps/api/geocode/xml?latlng=" . $lat . "," . $lng . "&sensor=false");

foreach($xml->result as $result)
{
    foreach($result->address_component as $addresscomponent)
    {
        echo $addresscomponent->long_name . ' ';
    }

    echo '<br />';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜