0

This is my PHP code to find latitude and longitude of the location given.But when the location have 2 or more words it return error

ex: if $cityname have "Mexico City" then it returns error if it is only one word then it is return correctly

<?php
    function get_latlng($cityname)
    {
    $Url='http://maps.googleapis.com/maps/api/geocode/json?address='.$cityname.'&sensor=false';
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $output = curl_exec($ch);
    curl_close($ch);
    $search_data = json_decode($output);
    $new = array("lat"=>$search_data->results[0]->geometry->location->lat,"lng"=>$search_data->results[0]->geometry->location->lng);
    return $new;
    }
    ?>

This is the error produced

<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">



<h4>A PHP Error was encountered</h4>



<p>Severity: Notice</p>

<p>Message:  Trying to get property of non-object</p>

<p>Filename: admin/markers.php</p>

<p>Line Number: 19</p>



</div>

here admin/markers.php is my view page

this is the 19th line in my view page

$new = array("lat"=>$search_data->results[0]->geometry->location->lat,"lng"=>$search_data->results[0]->geometry->location->lng);
Mariya Davis
  • 11
  • 1
  • 6

3 Answers3

4

Try using urlencode() on $cityname to convert spaces.

$city = urlencode($cityname);
$Url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$city.'&sensor=false';
Doug Owings
  • 4,438
  • 1
  • 21
  • 21
1
Try:
function get_latlng($address) {
        $address = urlencode(trim($address));
        $details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $address . "&sensor=false";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $details_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = json_decode(curl_exec($ch), true);
        if ($response['status'] != 'OK') {
            return null;
        }
        $latLng = $response['results'][0]['geometry']['location'];
        return $latLng;
    }
    $response = get_latlng("Mexico City");
    print_r($response);

Array ( [lat] => 19.4326077 [lng] => -99.133208 )
Indrajeet Singh
  • 2,958
  • 25
  • 25
1

Change your URL curl won't read space in URL so you have to convert special characters with respective ascii

Here UR URL will be something like below.

http://maps.googleapis.com/maps/api/geocode/json?address=Mexico%20City&sensor=false

Please Note it should be "Mexico%20City" not "Mexico City"

rest your code is working fine for me.

pinaldesai
  • 1,835
  • 2
  • 13
  • 22