使用JavaScript或PHP从地址返回经度和纬度的基本API

使用JavaScript或PHP从地址返回经度和纬度的基本API

问题描述:

I am quite new to JavaScript and I am looking for a basic API or function that I can feed an address as a string value and it returns me the longitude and latitude of that address. I have a series of addresses in a DB and I want to add the longitude and latitude values for each of them.

Thanks

我是JavaScript的新手,我正在寻找一个基本的API或函数,我可以将地址作为 字符串值,它返回该地址的经度和纬度。 我在DB中有一系列地址,我想为每个地址添加经度和纬度值。 p>

谢谢 p> div>

Find below example using php

<?php
$address ="1600+Amphitheatre+Parkway,+Mountain+View,+CA";
$url ="http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=false";
$getAddress = simplexml_load_file($url);
print"<pre>";
print_r($getAddress);
?>

It return all detail you need to get latitude/longitude as below.

<?php
print"<pre>";
print_r((string)$getAddress->result->geometry->location->lat); echo "<br />";
print_r((string)$getAddress->result->geometry->location->lng);
?>

For more detail please click on below link:

http://code.google.com/apis/maps/documentation/geocoding/

This is called Geocoding and is quite easy to do with the Google Maps API:

http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests

   function GetLatLong($address){
    $myKey = 'Get key from google api v2 ';
        $URL = "http://maps.google.co.uk/maps/geo?q=" . urlencode($address) . "&output=xml&key=".$myKey;
        $xml = simplexml_load_file($URL);
        $status = $xml->Response->Status->code;
        if ($status=='200') 
        { //address geocoded correct, show results
            foreach ($xml->Response->Placemark as $node) 
            { // loop through the responses
                $address = $node->address;
                if(strpos($address,'USA') || strpos($address,'usa'))
                {
                    $quality = $node->AddressDetails['Accuracy'];
                    $coordinates = $node->Point->coordinates;
                    return (explode(',',$coordinates));
                }
            }
        }
    }

This api will only work for usa and uk addresses . The address should be separated with '+' and should not contain any spaces. This code is only parsing coordinates for usa . Please modify the code according to your requirement