0

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.

asprin
  • 9,579
  • 12
  • 66
  • 119
  • Google server does not allow request directly from the server unless it is triggered using browser agent. What are you trying to achieve by CURL + Google Map? – Anand G Sep 28 '16 at 07:02
  • @AnandG Getting the lat and lng from a text address. – asprin Sep 28 '16 at 07:03

2 Answers2

1

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);
Anigel
  • 3,435
  • 1
  • 17
  • 23
  • My bad. I posted the old code. I was URL encoding the parameters only and not the entire URL. – asprin Sep 28 '16 at 07:14
  • In which case you shouldn't get the error you gave as that code works as long as you have a valid key – Anigel Sep 28 '16 at 07:15
0

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?

Community
  • 1
  • 1
bamnet
  • 2,525
  • 17
  • 21