Com o google maps cada vez mais difundido entre a população. Pela facilidade na utilização do aplicativo e pelos benefícios providos pelo mesmo. Está cada vez mais comum, nos depararmos com sites e sistemas utilizando tais funcionalidades do aplicativo, para indicar a localização de empresas, rotas e outros pontos interessantes.
O Google disponibiliza uma API para que os desenvolvedores utilizem os recursos do GMap.
Na demonstração a seguir será abordado funcionalidades simples da API do GMaps, como:
- Marcar um ponto no mapa pelo endereço
- Marcar um ponto no mapa pela localização (Latitude e Longitude)
- Criar descrição de rotas
- Criar eventos para receber o endereço atual do marcador ao arrastá-lo
- Customizar ícones dos marcadores com imagens diferentes do padrão
- Definir a fronteira e o zoom do mapa, de acordo com todos os pontos adicionados nele
Para você ter uma ideia de como ficará, segue um printscreen do resultado final.

Faça o download do demo: https://github.com/maxclaus/GoogleMapsAPI3
var map;
var directionsPanel;
var directions;
var from;
var to;
var urlPrint;
var lat, lng;
var bounds;
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();
function CarregarMapa() {
map = new google.maps.Map(document.getElementById('gmap'), {
'zoom': 3,
'center': new google.maps.LatLng(70, 0),
'mapTypeId': google.maps.MapTypeId.ROADMAP
});
bounds = new google.maps.LatLngBounds();
marker1 = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(65, -10),
draggable: true,
title: 'Arraste-me!'
});
bounds.extend(new google.maps.LatLng(65, -10));
lat = parseFloat($("#hdnLatitude").val());
lng = parseFloat($("#hdnLongitude").val());
marker2 = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lng),
draggable: true,
icon: 'http://google-maps-icons.googlecode.com/files/airport.png'
});
bounds.extend(new google.maps.LatLng(lat, lng));
google.maps.event.addListener(marker1, "drag", function () {
var latLng = marker1.getPosition();
$("#txtLatitude").val(latLng.lat());
$("#txtLongitude").val(latLng.lng());
$("#hdnLatitude").val(latLng.lat());
$("#hdnLongitude").val(latLng.lng());
});
google.maps.event.addListener(marker1, "dragend", function () {
geocodePosition(marker1.getPosition());
});
google.maps.event.addListener(marker1, "click", function () {
marker.openInfoWindowHtml("Arraste o ponto, para definir a localização");
});
map.fitBounds(bounds);
map.setZoom(map.getZoom());
map.setCenter(bounds.getCenter());
}
function AdicionarLocalizacao() {
var marker3 = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(-70, -10),
draggable: true,
title: 'Arraste-me!',
icon: 'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-ff8a22/shapecolor-white/shadow-1/border-color/symbolstyle-color/symbolshadowstyle-no/gradient-no/archery.png'
});
bounds.extend(new google.maps.LatLng(-70, -10));
map.fitBounds(bounds);
map.setZoom(bounds.getZoom());
map.setCenter(bounds.getCenter());
}
function CarregarPeloEndereco() {
var endereco = $('#txtEndereco').val();
geocoder.geocode({
address: endereco
}, function (responses) {
if (responses && responses.length > 0) {
var place = responses[0];
var marker4 = new google.maps.Marker({
map: map,
position: place.geometry.location,
draggable: true,
title: 'Arraste-me!',
icon: 'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-ffc11f/shapecolor-color/shadow-1/border-dark/symbolstyle-white/symbolshadowstyle-dark/gradient-no/scoutgroup.png'
});
bounds.extend(place.geometry.location);
$('#txtEnderecoImovel').val(place.formatted_address);
map.fitBounds(bounds);
map.setZoom(map.getZoom());
map.setCenter(bounds.getCenter());
} else {
$('#txtEndereco').val('Nao pode determinar a localizacao.');
}
});
}
function CriarRota() {
if (Trim($("#ondeestou").val()) == "") {
alert("Preencha a sua localizacao.");
return;
}
directionsPanel = document.getElementById("rota_gmap");
directionsPanel.innerHTML = "";
from = $("#ondeestou").val();
var directionsDisplay = new google.maps.DirectionsRenderer({
'map': map,
'preserveViewport': true,
'draggable': true
});
directionsDisplay.setPanel(directionsPanel);
var request = {
origin: from,
destination: new google.maps.LatLng(lat, lng),
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function (responses) {
if (responses && responses.length > 0) {
$('#txtEndereco').val(responses[0].formatted_address);
} else {
$('#txtEndereco').val('Nao pode determinar a localizacao.');
}
});
}
function Trim(str) {
return str.replace(/^s+|s+$/g, "");
}
function Imprimir() {
var disp_setting = "toolbar=yes,location=no,directories=yes,menubar=yes,";
disp_setting += "scrollbars=yes,width=643, height=600, left=100, top=25";
var content_vlue = document.getElementById("rota_gmap").innerHTML;
var docprint = window.open("", "", disp_setting);
docprint.document.open();
docprint.document.write("<html><head><title>Como chegar</title>");
docprint.document.write("<style type="text/css">body{ font-family:Tahoma;font-size:8pt; margin:10px; }</style>");
docprint.document.write("</head><body><center>");
docprint.document.write("<h1>Como chegar</h2>");
docprint.document.write("<div style="width: 603px; margin-left:2px;">");
docprint.document.write(content_vlue);
docprint.document.write("</div>");
docprint.document.write("<script type="text/javascript" language="javascript">window.print();</script></body></html>");
docprint.document.close();
docprint.focus();
}
<html>
<head>
<title>Google Maps API</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="css/common.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/js-gmaps-functions.js"></script>
<script type="text/javascript" language="javascript">
$(function () {
CarregarMapa();
});
</script>
</head>
<body>
<div id="wrapper">
<input id="hdnLatitude" runat="server" type="hidden" value="-23.292757" />
<input id="hdnLongitude" runat="server" type="hidden" value="-51.169424" />
<div>
<div class="box_left">
<label> Endereço:</label>
<input type="text" id="txtEndereco" value="Av. Tiradentes 1241, Londrina PR" size="54" />
<a class="button" href="javascript:CarregarPeloEndereco();" title="Carregar a partir do endereço">
<img src="img/search.png" alt="Buscar" />
</a>
<div class="box_middle">
<label> Latitude:</label>
<input type="text" id="txtLatitude" value="-23.292757" />
</div>
<div class="box_middle">
<label> Longitude:</label>
<input type="text" id="txtLongitude" value="-51.169424" />
<a class="button" href="javascript:CarregarMapa();" title="Carregar a partir da longitude e latitude">
<img src="img/search.png" alt="Buscar" />
</a>
</div>
<div>
<label>
Adicionar mais 1 localização
<a class="button" href="javascript:AdicionarLocalizacao();">
<img src="img/add.png" alt="Add" />
</a>
</label>
</div>
</div>
<div class="box_right">
<label> Como chegar?</label>
<input type="text" id="ondeestou" size="36" />
<a href="javascript:CriarRota();" title="Traçar Rota" class="button"> <img src="img/go.png" alt="Ir" /></a>
<br />
<span style="font-size: 8pt; color: #999;">Ex: Rua Numero, Cidade, Estado</span>
<br />
<br />
<a href="javascript:Imprimir();" class="button">
<img src="img/print.png" alt="Imprimir" /><span>Imprimir rota</span>
</a>
</div>
</div>
<div>
<div class="box_left">
<div id="gmap"></div>
</div>
<div class="box_right">
<div id="rota_gmap"></div>
</div>
</div>
</div>
</body>
</html>