Traçar rota do endereço mais próximo com a API do Google Maps

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" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="<a href="http://www.w3.org/1999/xhtml">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="<a href="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAh-4-WXT7vryB4zWcSDKIThSuBLcACnbYAIBxS9eHfruCpUv1BBRZi-GSNoVlnTofbgShokT-TgG8BA">http://maps.google.com/maps?file=api&v=2&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>
</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" 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!

Posts relacionados:

  1. Como buscar informações detalhadas de um endereço como a Latitude e Longitude com a API do Google Maps
  2. Calcular distância entre dois ponto GPS (latitude e longitude) em PHP
  3. Escrevendo uma Classe Singleton no Javascript
  4. PHP + JSON
  5. (aula 3) AJAX para Iniciantes – Recuperando dados XML com AJAX

About the Author

Lucas Martins é formado em Sistemas para Internet na FIAP, tem 22 anos e mora na capital de São Paulo. Interessado em tecnologias inovadoras, pretende destacar no blog sobre algumas das tecnologias mais utilizadas e procuradas da internet hoje, o AJAX. Também dará algumas dicas importantes no desenvolvimento de sistemas utilizando o PHP 5, como também discutir outras tecnologias que possam mudar, ou melhor, otimizar a web.