Fala amigos, estive precisando de um script que traçava a rota do endereço (previamente marcado) mais próximo com o endereço que eu digitei.

Eu encontrei um script no blog andafter.org e melhorei ele, segue o script:

observação: A distância que a API utiliza para calcular é uma distância reta do ponto A para o ponto B. Se você quer saber a distância da rota, deverá utilizar o método getDistance(). Se eu ver que muita gente precisará disso eu criarei um post ensinando como faz.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Endereço mais próximo utilizando a API do Google Maps | Por Lucas Martins</title>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAh-4-WXT7vryB4zWcSDKIThSuBLcACnbYAIBxS9eHfruCpUv1BBRZi-GSNoVlnTofbgShokT-TgG8BA" type="text/javascript"></script>
<script type="text/javascript">
/*
	variáves globais / globals vars
*/
var geocoder = new GClientGeocoder();
var map;
var directionsPanel;
var directions;
var gdir = new GDirections();
var addr = new Array(3);
var distances = new Array(3);

// Ao carregar / After load
window.onload = function() {

	// Seta o país que será usado na API / Set the country that will be used in the API
	geocoder.setBaseCountryCode("pt_BR");

	map = new GMap2(document.getElementById('map'), { size: new GSize(710,480) })
	map.addControl(new GLargeMapControl());
	map.setCenter(new GLatLng(-23.547779, -46.639366), 12); // São Paulo / Sao Paulo (brazilian city)

	// Adiciona marcação dos endereços das bibliotecas públicas de São Paulo / Add marks of addresses of public libraries in Sao Paulo
	showAddress("Rua Cisplatina, 505 - Ipiranga, São Paulo - SP, 04211-040", 1);
	showAddress("Rua Arsênio Tavolieri, 45 - Jabaquara, São Paulo - SP, 04321-030", 2);
	showAddress("Rua Sena Madureira, 298 - Vila Mariana, São Paulo - SP, 04021-050", 3);

	// No clique do botão / On click of button
	document.getElementById("trace_route").onclick = function() {

		// Verifica o endereço digitado pelo usuário / Check the address entered by the User
		geocoder.getLocations(
			document.getElementById("myAddress").value,
			function(point) {
				// Verifica se o endereço que o usuário digitou é válido e existente / Check if the address that the user entered is valid and existing
				if(point.Placemark) {

					// Cria o objeto GLatLng e grava a latitude e longitude do endereço digitado pelo usuário
					// Creates the GLatLng object and records the latitude and longitude of the address entered by the User
					var a = new GLatLng(point.Placemark[0].Point.coordinates[1], point.Placemark[0].Point.coordinates[0]);

					/*
						usa método da classe GLatLng() que retorna a distância, em metros, entre
						duas coordenadas de latitude/longitude

						use method of the GLatLng() which returns the distance in meters between
						two latitude / longitude
					*/
					var b = new GLatLng(addr[0][1], addr[0][0]); // inicia no primeiro ponto / start in the first point
					var x = b.distanceFrom(a);

					/*
						variáveis que serão usadas para comparar distâncias entre coordenadas
						de latitude e longitude

						variables that will be used to compare distances between coordinates
						latitude and longitude
					*/
					var smallestDist = x;
					var smallestDistId = 0;

					//
					for(var i = 0; i < 3; i++) {

						b = new GLatLng(addr[i][1], addr[i][0]);
						x = b.distanceFrom(a);

						// Verifica qual dos endereços tem menor distância entre um ponto e outro
						// Check It addresses which is less distance between one point and another
						if(x < smallestDist || i == 0) {
							smallestDist = x;
							smallestDistId = i;
						}
					}

					/*
						cria um array de dois objetos GLatLng, com as coordenadas do endereço digitado pelo
						usuário e o endereço do ponto mais próximo a esse endereço

						creates an array of two GLatLng objects, with the coordinates of the address entered by
						User and address of the nearest point to this address
					*/

					var pointsArray = [a, new GLatLng(addr[smallestDistId][1], addr[smallestDistId][0])]
					directions = new GDirections(map); // instancia objetos / instance objects
					// usa o array de pontos para traçar a rota entre os dois endereços / uses the array of points to trace the route between two addresses
					directions.loadFromWaypoints(pointsArray, {"locale":"pt_BR"});
				}
			}
		);
	}
}

/*
	função que será usada para manipular endereços
	function that will be used to manipulate addresses
*/
function showAddress(address, k) {
	geocoder.getLocations(
		address,
		function(point) {
			addMarker(point, k);
		}
	);
}

/*
	função que será usada para marcar o mapa
	function that will be used to mark the map
*/
function addMarker(response, k) {
	if(!response.Placemark) { return; }
	place = response.Placemark[0];
	if(k) {
		// salva a latitude/longitude do endereço / save the latitute/longitude of address
		addr[k-1] = place.Point.coordinates;
	}
	point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
	var marker = createMarker(point, place.address, k); // cria o marcador no mapa / creates the marker on the map
	map.addOverlay(marker); // adiciona o marcador no mapa / adds the marker on the map
}

/*
	função que será usada para criar os marcadores
	function that will be used for creating markers
*/
function createMarker(point,html, k) {
	var marker = new GMarker(point, false);
	return marker;
}
</script>
</head>

<body>
<form action="#" method="POST">
    <fieldset>
        <label for="from">Seu endereço:</label>
        <input type="text" name="myAddress" id="myAddress" />
    </fieldset>
    <input type="button" class="button" id="trace_route" value="Encontrar biblioteca próxima" />
</form>
<div id="map"></div>
</body>
</html>

Com algumas modificações desse código você também poderá obter todos os locais num raio de 100 metros de um endereço digitado. Ou um monte de outras situações.

Abraços!

Este é um exemplo de extração de dados da geocodificação utilizando a API do Google Maps

Este é um exemplo de extração de dados da geocodificação utilizando a API do Google Maps

Fala galerá, esta API do Google Maps é muito boa quando você precisa trabalhar com mapas, endereços, ceps, etc. Vou mostrar para vocês um exemplo de código que traz informações detalhadas sobre um endereço.

Vou utilizar como exemplo o endereço:

Rua Vergueiro, 1000 (é o endereço do Centro Cultural de São Paulo que fica na Vergueiro)

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Buscar Informações detalhadas do endereço</title>
<script src=”http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAh-4-WXT7vryB4zWcSDKIThSuBLcACnbYAIBxS9eHfruCpUv1BBRZi-GSNoVlnTofbgShokT-TgG8BA” type=”text/javascript”></script>
<script type=”text/javascript”>
var map = null;
var geocoder = null;

function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById(“mapa”));
map.setCenter(new GLatLng(34, 0), 1);
geocoder = new GClientGeocoder();
}
}

function showAddress(address) {
if (geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + ” não encontrado”);
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(address);
}
}
);
}
}

// addAddressToMap() é chamado quando o geocoder retorna uma
// resposta. Ele adiciona um marcador no mapa com uma janela aberta
// mostrando uma boa formatação do endereço, o código do país, latitude, longitude e o CEP.
function addAddressToMap(response) {
map.clearOverlays();
if (!response || response.Status.code != 200) {
alert(“Desculpe, não fomos capazes de geocodificar o endereço”);
} else {
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(place.address + ‘<br>’ +
‘<b>Código do páis:</b> ‘ + place.AddressDetails.Country.CountryNameCode + ‘<br>’ +
‘<b>Latitude:</b>’ + place.Point.coordinates[1] + ‘<br>’ +
‘<b>Longitude:</b>’ + place.Point.coordinates[0] + ‘<br>’ +
‘<b>CEP:</b>’ + place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber);
map.setCenter(point, 13);
}
}

// showLocation() é chamado quando você clica no botão de buscar
// no formulario.
function showLocation() {
var address = document.getElementById(‘address’).value;
geocoder.getLocations(address, addAddressToMap);
}
</script>
</head>

<body onload=”initialize()” onunload=”GUnload()”>
<form action=”#” onsubmit=”showLocation(); return false”>
<p>
<input type=”text” size=”60″ name=”address” id=”address” value=”Rua Vergueiro, 1000″ />
<input type=”submit” value=”Go!” />
</p>
<div id=”mapa” style=”width: 500px; height: 300px”></div>
</form>
</body>
</html>

Foi testado e está funcionando, você só precisa trocar a key de uso da API do Google Maps acessando este link: http://code.google.com/intl/pt-BR/apis/maps/signup.html

 Para mais detalhes deste recurso da API do Google Maps, veja este link:

http://code.google.com/intl/pt-BR/apis/maps/documentation/services.html#Geocoding_Structured

 

Abraços!

Seguir

Obtenha todo post novo entregue na sua caixa de entrada.