I created a form where the person types where they are, and then a search is performed and a route is defined.
The question is: its starting point after the route is set is not appearing the icon that I created at the beginning of the code. How do I display the icon I created at the beginning of the route after the search is made? Or how to customize from my code an icon for the starting point and another for the endpoint after the search?
Script:
// Definindo as variaveis
var geocoder;
var map;
var marker = 'imagens/assets/marker.png';
var directionsService = new google.maps.DirectionsService();
// Iniciando o map
function initialize() {
var latlng = new google.maps.LatLng(-18.898123, -48.265920);
var options = {
zoom: 18,
center: latlng,
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
};
map = new google.maps.Map(document.getElementById("mapa"), options);
geocoder = new google.maps.Geocoder();
// Marcador Personalizado
marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
icon: marker
});
marker.setPosition(latlng);
// Parâmetros do texto que será exibido no clique;
var contentString = '<h2>Sertões PetShop</h2>' +
'<p>Av. Brasil, 2909 - B. Brasil</p>' +
'<p>Uberlândia-MG' +
'<p>38400-718</p>' +
'<a href="http://www.marcozeropetshop.com.br" target="_blank">www.sertoespetshop.com.br</a>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 700
});
// Exibir texto ao clicar no ícone;
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
// Infowindow delay
setTimeout(function() { infowindow.open(map, marker) }, 1700);
// Estilizando o map
var styles = [
{ stylers: [ { hue: "#41a7d5" }, { saturation: 60 }, { lightness: -20 }, { gamma: 1.51 } ] },
{ featureType: "road", elementType: "geometry",
stylers: [
{ lightness: 100 },
{ visibility: "simplified" }
]
},
{ featureType: "road", elementType: "labels" }
];
// crio um objeto passando o array de estilos (styles) e definindo um nome para ele;
var styledMap = new google.maps.StyledMapType(styles, {
name: "Mapa Style"
});
// Aplicando as configurações do mapa
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
}
// Lendo o documento e iniciando a function map
$(document).ready(function () {
initialize();
// CARREGANDO O MAPA
function carregarNoMapa(endereco) {
geocoder.geocode({ 'address': endereco + ', Brasil', 'region': 'BR' }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
$('#txtEndereco').val(results[0].formatted_address);
$('#txtLatitude').val(latitude);
$('#txtLongitude').val(longitude);
var location = new google.maps.LatLng(latitude, longitude);
marker.setPosition(location);
map.setCenter(location);
map.setZoom(16);
}
}
})
}
// CAPTURANDO AS POSIÇÕES E RESULTANDO
google.maps.event.addListener(marker, 'drag', function () {
geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#txtEndereco').val(results[0].formatted_address);
$('#txtLatitude').val(marker.getPosition().lat());
$('#txtLongitude').val(marker.getPosition().lng());
}
}
});
});
// Autocomplete dinâmico
$("#txtEndereco").autocomplete({
source: function (request, response) {
geocoder.geocode({ 'address': request.term + ', Brasil', 'region': 'BR' }, function (results, status) {
response($.map(results, function (item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
});
// Obtendo a latitude e longitude
$("#btnEndereco").click(function(){
var directionsDisplay = new google.maps.DirectionsRenderer();
var request = {
origin: $("#txtEndereco").val(),
destination: new google.maps.LatLng(-18.898123, -48.265920),
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var leg = response.routes[0].legs[0];
var mStart = new google.maps.Marker({
icon: 'imagens/assets/marker.png',
position: leg.start_location,
map: map
});
var mEnd = new google.maps.Marker({
icon: 'imagens/assets/marker-final.png',
position: leg.end_location,
map: map
});
directionsDisplay.setDirections(response);
directionsDisplay.setOptions({
suppressMarkers: true,
polylineOptions: {
strokeWeight: 6,
strokeOpacity: 0.7,
strokeColor: '#0C47A0'
}
});
directionsDisplay.setMap(map);
}
});
});
// Realizando a busca depois do clique
$("form").submit(function(event) {
event.preventDefault();
var endereco = $("#txtEndereco").val();
var latitude = $("#txtLatitude").val();
var longitude = $("#txtLongitude").val();
alert("Endereço: " + endereco + "\nLatitude: " + latitude + "\nLongitude: " + longitude);
});
});
Form:
<form method="post" action="">
<fieldset>
<div class="campos" style="margin: 15px;">
<input type="text" id="txtEndereco" name="txtEndereco" size="50" style="padding: 15px; border: 1px solid #cdcdcd;" placeholder="Onde estou..."/>
<input type="button" id="btnEndereco" name="btnEndereco" value="VER ROTA" style=" padding: 15px;" />
</div>
<div id="mapa"></div>
<input type="hidden" type="submit" value="Enviar" name="btnEnviar" />
<input type="hidden" id="txtLatitude" name="txtLatitude" />
<input type="hidden" id="txtLongitude" name="txtLongitude" />
</fieldset>
</form>