User login

Getting latitude and longitude for countries, provinces, or cities

Stolen from Dwees in this comment:

  $city = $node->location['city'];
  $province = $node->location['province'];
  $country = $node->location['country'];

  $address = str_replace(" ", "+", $city .",". $province .",". $country);
  $google_key = variable_get('googlemap_api_key', '');

  $url = "http://maps.google.com/maps/geo?q=" . $address ."&output=csv&key=". $google_key;

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  $text = curl_exec($ch);
  curl_close($ch);

  $location = explode(",", $text);
  $latitude = $location[2];
  $longitude = $location[3];

  echo '<p>';
  if (!is_null($latitude) && !is_null($longitude) && !($latitude == 0 && $longitude == 0) && $row['vid']) {

Turned it into this:

Resolution

<pre>
/**
* Place latitude and longitude
*
* @param place
* An array with a country and, optionally, a state and town
* proceeding in the order city, province, country
*
* @return
* An array with latitude and longitude
*/
function place_taxonomy_lat_lon($place) {
  $q = str_replace(' ', implode(',',$place));
  $url = 'http://maps.google.com/maps/geo?q=' . $q . '&output=csv&key=' . variable_get('googlemap_api_key', '');

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  $c = curl_exec($ch);
  curl_close($ch);
drupal_set_message('<pre>' . print_r($c, TRUE) . '</pre>');
  $loc = explode(',', $c);
  $lat = $location[2];
  $lon = $location[3];

  if (!is_null($lat) && !is_null($lon) && !($lat == 0 && $lon == 0)) {
    return array($lat, $lon);
  }
}
</pre>

NOTE: Final code in place module has changed still a bit more. Uses JSON for starters.

Probably still fragile and insecure.

Searched words: 
country latlon geolocation place latitude longitude geographical coordinates

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.