asprin
asprin

Reputation: 9823

Google Maps API not working with server side code but works client side

I'm generating a URL such as:

http://maps.googleapis.com/maps/api/geocode/json?address=143+Blackstone+Street%2C+Mendon%2C+MA+-+01756&key=***********

If I open this in browser, I'm getting a result successfully. However, if I use the same URL using curl, I'm getting:

error:couldn't connect to host

Here is my PHP code

$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode('143 Blackstone Street, Mendon, MA - 01756')."&key=***********";    
$ch = curl_init();
$options = array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_TIMEOUT => 100,            
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_SSL_VERIFYPEER => false
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if(curl_error($ch))
{
    echo 'error:' . curl_error($ch);
}
curl_close ($ch);
print_r($response);

UPDATE

I came across a term called as server key and browser key when using the Google APIs. Howerver, in the API manager, I can't seem to see where to set or change the API type.

Upvotes: 0

Views: 925

Answers (2)

bamnet
bamnet

Reputation: 2554

If you're hitting an 'couldn't connect to host' error message from curl it sounds like the problem may not be on the Google Maps API side and instead be on the proxy / networking side. A connection to maps.googleapis.com should always be possible, regardless of key type or url params.

I would look into the steps suggested here: How to resolve cURL Error (7): couldn't connect to host?

Upvotes: 0

Anigel
Anigel

Reputation: 3437

You are urlencodeing parts of the url that need to be in plain text.

Only urlencode your parameters

<?php
$address = urlencode("143 Blackstone Street, Mendon, MA - 01756");
$key = urlencode("************");
$ch = curl_init();
$options = array(
    CURLOPT_URL => "http://maps.googleapis.com/maps/api/geocode/json?address=".$address."&key=".$key,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_TIMEOUT => 100,
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_SSL_VERIFYPEER => false
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if(curl_error($ch))
{
    echo 'error:' . curl_error($ch);
}
curl_close ($ch);
print_r($response);

Upvotes: 1

Related Questions