Kiran Dash
Kiran Dash

Reputation: 4956

Right way of preparing address for google map json geocode

I am trying to get lat and lng values from an address using the following PHP script:

    $address = "G & D KOI & AQUARIA, KLEINE VELD, DALEN, Nederland";
    $prepAddr = str_replace(' ','+',$address);
    $prepAddr = str_replace('&','%26',$prepAddr);
    $geocode = file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
    $output= json_decode($geocode);
    $lat = $output->results[0]->geometry->location->lat;
    $lng = $output->results[0]->geometry->location->lng;

I am replacing & with %26. and ' ' with '+'. Do I need to take care of anything else?

Upvotes: 0

Views: 38

Answers (1)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

Try this:

$prepAddr = urlencode($prepAddr);

and use the $prepAddr in your API code just like you are using.

urlencode — URL-encodes string

string urlencode ( string $str )

This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.

Upvotes: 1

Related Questions