Ottenere le coordinate di un luogo con le Google Maps in PHP e jQuery

Ottenere le coordinate di un luogo con le Google Maps in PHP e jQuery

In PHP possiamo utilizzare le API pubbliche delle Google Maps per ottenere le coordinate (latitudine e longitudine) di un indirizzo o località passato come parametro dell'URL. Vediamo in dettaglio questa caratteristica.

Implementazione PHP

La seguente funzione accetta come argomento un indirizzo e restituisce un array associativo contenente la latitudine e longitudine della località specificata:


function getLatLong( $address )
{
	if (!is_string($address) ){
	
		die('Gli indirizzi devono essere stringhe');
	}
	
	$url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address));
	
	$result = false;
	
	if($result = file_get_contents($url)) {
	
	    $coords = array();
	
		if(strpos($result,'errortips') > 1 || strpos($result,'Did you mean:') !== false) {
			 return false;
		}
		
		preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $result, $matches);
		
		$coords['lat'] = $matches[1];
		$coords['long'] = $matches[2];
	}
	
	return $coords;
}

Integrazione con jQuery

La funzione può essere modificata per funzionare tramite AJAX con jQuery. Per prima cosa dobbiamo impostare uno script PHP che riceva la richiesta AJAX:


header('Content-Type: application/json');
$address = $_GET['address'];
// validazione della variabile GET

Quindi modifichiamo la funzione getLatLong() per farle restituire un oggetto JSON:


return json_encode($coords);

Infine la usiamo nel nostro script:


// validazione della variabile GET
echo getLatLong($address);
exit();

Con jQuery non dobbiamo far altro che catturare il valore di un campo di un form ed effettuare la richiesta AJAX:


$('#google-address-form').submit(function(e) {

	e.preventDefault();
	
	var address = $('#address').val();
	
	$.ajax({
		url: 'script.php',
		type: 'GET',
		dataType: 'json',
		data: 'address=' + address, // qui potete usare encodeURIComponent()
		success: function(json) {
		
			var lat = json.lat;
			var long = json.long;
		
		
		}
	});
	


});

Se usate encodeURIComponent() (scelta consigliata), dovete ricordarvi di non utilizzare la funzione rawurlencode() nella funzione PHP, in quanto la stringa passata è già stata codificata.

Torna su