简体   繁体   中英

Basic API that returns longitude and latitude from an address using JavaScript or PHP

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

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

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

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/

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM