Rectangle 27 2

1) You need a PHP loop to iterate the result set from the query, and then generate a javascript array of addresses.

var address = '<?php echo $address.', '.$city.', '.$state; ?>';
var addresses = [];
<?php while ($row = mysql_fetch_assoc($my_query)) { ?>
addresses.push(<?php echo '"' . $row['address'].', '.$row['city'].', '.$row['state'] . '"'; ?>);
<?php } ?>

2) Wrap a javascript loop around your geocoder.geocode function call, to iterate over the addresses array you just generated.

for(i in addresses) {
    var address = addresses[i];
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map, 
                position: results[0].geometry.location
            });
        } else {
            // alert("Geocode was not successful for the following reason: " + status);
        }
    });

Thanks for the reply. It's way past bedtime, but I can't wait to try this in the morning. I'll let you know how it goes.

I tried this solution but just couldn't get it to work. Instead of showing all the listings and only mapping the first listing, now the page shows only the first listings and the map doesn't show at all.

php - Google Maps (api v3) - Loop through mysql query results to geoco...

php mysql google-maps google-maps-api-3
Rectangle 27 31

<?php
  $Address = urlencode($Address);
  $request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$Address."&sensor=true";
  $xml = simplexml_load_file($request_url) or die("url not loading");
  $status = $xml->status;
  if ($status=="OK") {
      $Lat = $xml->result->geometry->location->lat;
      $Lon = $xml->result->geometry->location->lng;
      $LatLng = "$Lat,$Lon";
  }
?>

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Google Maps - converting address to latitude & longitude - PHP backend...

php google-maps geocoding
Rectangle 27 7

<?php

/* 
* Given an address, return the longitude and latitude using The Google Geocoding API V3
*
*/

function Get_LatLng_From_Google_Maps($address) {
    $address = urlencode($address);

    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false";

    // Make the HTTP request
    $data = @file_get_contents($url);
    // Parse the json response
    $jsondata = json_decode($data,true);

    // If the json data is invalid, return empty array
    if (!check_status($jsondata))   return array();

    $LatLng = array(
        'lat' => $jsondata["results"][0]["geometry"]["location"]["lat"],
        'lng' => $jsondata["results"][0]["geometry"]["location"]["lng"],
    );

    return $LatLng;
}

/* 
* Check if the json data from Google Geo is valid 
*/

function check_status($jsondata) {
    if ($jsondata["status"] == "OK") return true;
    return false;
}

/*
*  Print an array
*/

function d($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}

Google Maps - converting address to latitude & longitude - PHP backend...

php google-maps geocoding
Rectangle 27 5

<?php

/* 
* Given longitude and latitude in North America, return the address using The Google Geocoding API V3
*
*/

function Get_Address_From_Google_Maps($lat, $lon) {

$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";

// Make the HTTP request
$data = @file_get_contents($url);
// Parse the json response
$jsondata = json_decode($data,true);

// If the json data is invalid, return empty array
if (!check_status($jsondata))   return array();

$address = array(
    'country' => google_getCountry($jsondata),
    'province' => google_getProvince($jsondata),
    'city' => google_getCity($jsondata),
    'street' => google_getStreet($jsondata),
    'postal_code' => google_getPostalCode($jsondata),
    'country_code' => google_getCountryCode($jsondata),
    'formatted_address' => google_getAddress($jsondata),
);

return $address;
}

/* 
* Check if the json data from Google Geo is valid 
*/

function check_status($jsondata) {
    if ($jsondata["status"] == "OK") return true;
    return false;
}

/*
* Given Google Geocode json, return the value in the specified element of the array
*/

function google_getCountry($jsondata) {
    return Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"]);
}
function google_getProvince($jsondata) {
    return Find_Long_Name_Given_Type("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
}
function google_getCity($jsondata) {
    return Find_Long_Name_Given_Type("locality", $jsondata["results"][0]["address_components"]);
}
function google_getStreet($jsondata) {
    return Find_Long_Name_Given_Type("street_number", $jsondata["results"][0]["address_components"]) . ' ' . Find_Long_Name_Given_Type("route", $jsondata["results"][0]["address_components"]);
}
function google_getPostalCode($jsondata) {
    return Find_Long_Name_Given_Type("postal_code", $jsondata["results"][0]["address_components"]);
}
function google_getCountryCode($jsondata) {
    return Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"], true);
}
function google_getAddress($jsondata) {
    return $jsondata["results"][0]["formatted_address"];
}

/*
* Searching in Google Geo json, return the long name given the type. 
* (If short_name is true, return short name)
*/

function Find_Long_Name_Given_Type($type, $array, $short_name = false) {
    foreach( $array as $value) {
        if (in_array($type, $value["types"])) {
            if ($short_name)    
                return $value["short_name"];
            return $value["long_name"];
        }
    }
}

/*
*  Print an array
*/

function d($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}

Feel free to look at my blog for a sample code of how using the code above and sample result.

geolocation - PHP Latitude Longitude to Address - Stack Overflow

php geolocation location latitude-longitude
Rectangle 27 1

<?php

    $zipcode=$_POST('zipcode');

    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$zipcode."&
            sensor=false";

    $details=file_get_contents($url);

    $result = json_decode($details,true);

    $account_lat=$result['results'][0]['geometry']['location']['lat'];

    $account_long=$result['results'][0]['geometry']['location']['lng'];

    echo "Latitude :" .$account_lat;

    echo '<br>';

    echo "Longitude :" .$account_long;

geocoding - What is a good API to find the latitude and longitude of a...

api geocoding latitude-longitude
Rectangle 27 1

I have a url like this, that search something in a location:

I need a list of the first 2 results like (Dentist Mr.Example1,Dentist Ex.2).

$searchTerm = 'dentist+austin+texas';

$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $searchTerm;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);

$array = json_decode($response, true);

// var_dump($array);

// Output

$array = $array['results'];

foreach($array as $index => $component)
{
    echo '#' . $index . ' ' . $component['formatted_address'] . '<br>';

    // show only the first 2 items (#0 & #1)
    if($index === 1) {
        break;
    }
}
  • Your search term is "dentist Austin textas" and that becomes 'dentist+austin+texas' when it's part of an URL.
  • The searchTerm is attached to the API URL.
  • This is turned into an $array by setting the second paramter of json_decode() to true.
  • For the display part: that's a simply array iteration. You can get rid of the top-level 'results' array by re-assigning the values to $array.
  • The output is a numbered list of dentists

The initial question was to list the first to results for dentists in austin,tx using the Google Maps API.

This additional requirement changes the API / webservice to use, in order to retrieve rich data. You want more details about the addresses. The data elements "phone_number" and "rating" are part of the Google Places Webservice (Place Details). You need to add your key to the request URLs (&key=API_KEY) in order to access this service.

1) From the first request you extract the "place_id"s.

2) With subsequent requests you retrieve the details about each place via the "Place Details" webservice.

Example: here i'm using the placeid for the first entry:

<?php

// Google GeoCode API
$address = 'dentist+austin+texas';

$array = getGoogleGeoCode($address);
$array = $array['results'];

//var_dump($array);

foreach($array as $index => $component)
{
    echo '#' . $index . ' ' . $component['formatted_address'] . ', ' ;

    // subsequent request for "Place Details"
    $details = getGooglePlaceDetails($component['place_id']);
    $details = $details['result'];
    //var_dump($details);

    echo 'Phone: ' . $details['formatted_phone_number']. ', ' ;

    // rating contains the place's rating, from 1.0 to 5.0, based on aggregated user reviews.
    if(isset($details['rating'])) {
        echo 'Rating: ' . $details['rating'];
    }

    // show only the first two entries
    /*if($index === 1) {
        break;
    }*/

    echo '<br>';
}

function getGooglePlaceDetails($placeid)
{
    // your google API key
    $key = 'AIzaSyCj9yH5x6_5_Om8ebAO2pBlaqJZB-TIViY';
    $url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=' . $placeid . '&key=' . $key;

    return curlRequest($url);
}

function getGoogleGeoCode($address)
{
    $url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $address;

    return curlRequest($url);
}

function curlRequest($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}
  • The array element rating is not always present, because it's review based. Just use var_dump($details); to see what is there and pick what you need.
  • To reduce the list, remove the comments around the break statement.

This is almost perfect, but I would like to get also the phone number and the ranking (stars for reviews).

I've updated my answer to include the "Place Details" requests. You might also use a radarSearch of the places API to reduce the number of requests. The details element rating is not always present (review based), just use var_dump($details); to see what is there and pick what you need.

How to get results names from Google Maps Api Search in PHP - Stack Ov...

php google-maps
Rectangle 27 0

<?php

    $zipcode=$_POST('zipcode');

    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$zipcode."&
            sensor=false";

    $details=file_get_contents($url);

    $result = json_decode($details,true);

    $account_lat=$result['results'][0]['geometry']['location']['lat'];

    $account_long=$result['results'][0]['geometry']['location']['lng'];

    echo "Latitude :" .$account_lat;

    echo '<br>';

    echo "Longitude :" .$account_long;

geocoding - What is a good API to find the latitude and longitude of a...

api geocoding latitude-longitude
Rectangle 27 0

It seems to be a bug in Geocode API. I have reported a bug to google web services.

php - Google Geocode API returns same result for different locations -...

php android ios google-api google-geocoding-api
Rectangle 27 0

"You need to replace & in the address argument by its URL-encoding %26"

{
   "results" : [],
   "status" : "ZERO_RESULTS"
}
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "2301",
               "short_name" : "2301",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "East Fowler Avenue",
... and so on ...
%26
place = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef) place,                                                                                      NULL, CFSTR("!*'();:@&=+$,/?%#[]\" "),                                                                                      kCFStringEncodingUTF8));

I'd have to look at Google API docs to see what the requirements are and escape only what they say to escape.

php - Google geocode API not returning result for certain locations - ...

php android ios google-api google-geocoding-api
Rectangle 27 0

You need to use the Google Geocode API to reverse geocode your address to obtain the co-ordinate which can then be used to display the results on the map. For example for my address I post to address parameters as given in the url below

http://maps.googleapis.com/maps/api/geocode/json?address=154+Metro+Central+Heights+London+UK&sensor=true

Co-ordinates can be obtained from the resulting JSON as shown below

"geometry": {
      "location": {
        "lat": 51.5001524,
        "lng": -0.1262362
      }
<?php

$address = $_GET['address'];
$address=str_replace(" ","+",$address);
if ($address) {
    $json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$address.
    '&sensor=true');
    echo $json;
}

?>

The Javascript can be found here. The critical code which parses the JSON is given below

$.getJSON("getjson.php?address="+address,
        function(data){
            lat=data.results[0].geometry.location.lat;
            lng=data.results[0].geometry.location.lng;
                        //.... more map initialization code
                 }
);

I had already set up a working example for your previous question here which should help you understand how to generate markers on the map. Let me know in case you need further clarification.

Ok, but what if I need to use XML instead of JSON? At this moment when I put "maps.googleapis.com/maps/api/geocode/json? anywhere Opera popups download window and asks where to download this "json" file...

Each browser has a different way of handling different file formats. If you intend to see the JSON format try opening it in firefox or chrome. If you need XML you need to replace json with xml like this http://maps.googleapis.com/maps/api/geocode/xml?address=your+address&sensor=true. I've shown you the json format because it easier to parse this either using plain javascript or jQuery.

Again please note that in Safari, XML is rendered differently as opposed to say IE. If you need to see the raw XML document in Safari you need to view the source. Do not how it is with Opera.

Thanks, but as I said before vertyhing with xml works fine, but have no idea how to parse :(

php - Google Geocode API result displaying on map? - Stack Overflow

php google-maps google-maps-api-3
Rectangle 27 0

<?php

/* 
* Given an address, return the longitude and latitude using The Google Geocoding API V3
*
*/

function Get_LatLng_From_Google_Maps($address) {
    $address = urlencode($address);

    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false";

    // Make the HTTP request
    $data = @file_get_contents($url);
    // Parse the json response
    $jsondata = json_decode($data,true);

    // If the json data is invalid, return empty array
    if (!check_status($jsondata))   return array();

    $LatLng = array(
        'lat' => $jsondata["results"][0]["geometry"]["location"]["lat"],
        'lng' => $jsondata["results"][0]["geometry"]["location"]["lng"],
    );

    return $LatLng;
}

/* 
* Check if the json data from Google Geo is valid 
*/

function check_status($jsondata) {
    if ($jsondata["status"] == "OK") return true;
    return false;
}

/*
*  Print an array
*/

function d($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}

Google Maps - converting address to latitude & longitude - PHP backend...

php google-maps geocoding
Rectangle 27 0

<?php
    $zipcode="92604";
    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$zipcode."&sensor=false";
    $details=file_get_contents($url);
    $result = json_decode($details,true);

    $lat=$result['results'][0]['geometry']['location']['lat'];

    $lng=$result['results'][0]['geometry']['location']['lng'];

    echo "Latitude :" .$lat;
    echo '<br>';
    echo "Longitude :" .$lng;
    ?>

google api - getting Latitude And Longitude From Pin Code Using PHP - ...

php google-api latitude-longitude
Rectangle 27 0

<?php

/* 
* Given longitude and latitude in North America, return the address using The Google Geocoding API V3
*
*/

function Get_Address_From_Google_Maps($lat, $lon) {

$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";

// Make the HTTP request
$data = @file_get_contents($url);
// Parse the json response
$jsondata = json_decode($data,true);

// If the json data is invalid, return empty array
if (!check_status($jsondata))   return array();

$address = array(
    'country' => google_getCountry($jsondata),
    'province' => google_getProvince($jsondata),
    'city' => google_getCity($jsondata),
    'street' => google_getStreet($jsondata),
    'postal_code' => google_getPostalCode($jsondata),
    'country_code' => google_getCountryCode($jsondata),
    'formatted_address' => google_getAddress($jsondata),
);

return $address;
}

/* 
* Check if the json data from Google Geo is valid 
*/

function check_status($jsondata) {
    if ($jsondata["status"] == "OK") return true;
    return false;
}

/*
* Given Google Geocode json, return the value in the specified element of the array
*/

function google_getCountry($jsondata) {
    return Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"]);
}
function google_getProvince($jsondata) {
    return Find_Long_Name_Given_Type("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
}
function google_getCity($jsondata) {
    return Find_Long_Name_Given_Type("locality", $jsondata["results"][0]["address_components"]);
}
function google_getStreet($jsondata) {
    return Find_Long_Name_Given_Type("street_number", $jsondata["results"][0]["address_components"]) . ' ' . Find_Long_Name_Given_Type("route", $jsondata["results"][0]["address_components"]);
}
function google_getPostalCode($jsondata) {
    return Find_Long_Name_Given_Type("postal_code", $jsondata["results"][0]["address_components"]);
}
function google_getCountryCode($jsondata) {
    return Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"], true);
}
function google_getAddress($jsondata) {
    return $jsondata["results"][0]["formatted_address"];
}

/*
* Searching in Google Geo json, return the long name given the type. 
* (If short_name is true, return short name)
*/

function Find_Long_Name_Given_Type($type, $array, $short_name = false) {
    foreach( $array as $value) {
        if (in_array($type, $value["types"])) {
            if ($short_name)    
                return $value["short_name"];
            return $value["long_name"];
        }
    }
}

/*
*  Print an array
*/

function d($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}

Feel free to look at my blog for a sample code of how using the code above and sample result.

geolocation - PHP Latitude Longitude to Address - Stack Overflow

php geolocation location latitude-longitude
Rectangle 27 0

1) You need a PHP loop to iterate the result set from the query, and then generate a javascript array of addresses.

var address = '<?php echo $address.', '.$city.', '.$state; ?>';
var addresses = [];
<?php while ($row = mysql_fetch_assoc($my_query)) { ?>
addresses.push(<?php echo '"' . $row['address'].', '.$row['city'].', '.$row['state'] . '"'; ?>);
<?php } ?>

2) Wrap a javascript loop around your geocoder.geocode function call, to iterate over the addresses array you just generated.

for(i in addresses) {
    var address = addresses[i];
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map, 
                position: results[0].geometry.location
            });
        } else {
            // alert("Geocode was not successful for the following reason: " + status);
        }
    });

Thanks for the reply. It's way past bedtime, but I can't wait to try this in the morning. I'll let you know how it goes.

I tried this solution but just couldn't get it to work. Instead of showing all the listings and only mapping the first listing, now the page shows only the first listings and the map doesn't show at all.

php - Google Maps (api v3) - Loop through mysql query results to geoco...

php mysql google-maps google-maps-api-3
Rectangle 27 -1

function getCoordinates($address){

$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern

$url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=$address";

$response = file_get_contents($url);

$json = json_decode($response,TRUE); //generate array object from the response from the web

return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);

}

How to call the function in php:

echo getCoordinates('740 Story Rd San Jose CA 95122');
Result : 37.328865,-121.8581845

Wow. I've never used PHP before. I should take some time to learn before implementing it.

Hah yeah I thought so. I am not using PHP.

Google Geocode Javascript API - How to get coordinates? - Stack Overfl...

javascript google-maps google-maps-api-3 geocoding