I'm using the GoogleMaps API to get the lat and long for an address, but strangely enough Google Maps causes PHP to run out of memory when a #
symbol is present in the string...
The code:
//some attempted addresses: "1234 Memory Lane Suite #1", "4321 Test Dr #4", "#"
$this->address = htmlentities($_POST['address']);
$googlemaps = new GoogleMaps(GOOGLE_MAPS_API_KEY);
$coordinates = $googlemaps->getCoordinates(
'UNITED STATES, ' .
$this->state . ', ' .
$this->city . ', ' .
$this->address
);
The error:
Allowed memory size of 268435456 bytes exhausted (tried to allocate 19574456 bytes)
When I strip out the pound symbol, everything works correctly. Just kind of curious what is Google's problem with the hash symbol?
Here's the source code of the API, It's pretty short:
class GoogleMaps {
/**
* The Google Maps API key holder
* @var string
*/
private $mapApiKey;
/**
* Class Constructor
*/
public function __construct() {
}
/**
* Reads an URL to a string
* @param string $url The URL to read from
* @return string The URL content
*/
private function getURL($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$tmp = curl_exec($ch);
curl_close($ch);
if ($tmp != false){
return $tmp;
}
}
/**
* Get Latitude/Longitude/Altitude based on an address
* @param string $address The address for converting into coordinates
* @return array An array containing Latitude/Longitude/Altitude data
*/
public function getCoordinates($address){
$address = str_replace(' ','+',$address);
$url = 'http://maps.google.com/maps/geo?q=' . $address . '&output=xml';
$data = $this->getURL($url);
if ($data){
$xml = new SimpleXMLElement($data);
$requestCode = $xml->Response->Status->code;
if ($requestCode == 200){
//all is ok
$coords = $xml->Response->Placemark->Point->coordinates;
$coords = explode(',',$coords);
if (count($coords) > 1){
if (count($coords) == 3){
return array('lat' => $coords[1], 'long' => $coords[0], 'alt' => $coords[2]);
} else {
return array('lat' => $coords[1], 'long' => $coords[0], 'alt' => 0);
}
}
}
}
//return default data
return array('lat' => 0, 'long' => 0, 'alt' => 0);
}
}; //end class`
Encode the address by using urlencode()
, otherwise the output-parameter will be ignored, because google handles the # as an anchor, not as a part of the q-parameter and the response will be json not xml