1
I created a form where the person type where it is and then a search is performed and a route is defined.
The question is: its starting point after the route is set is not showing the icon I created at the beginning of the code. How do I show the icon I created at the beginning of the route after the search is done? Or how to customize from my code an icon to the starting point and another to the ending point 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>
Paul, I changed the script but it doesn’t seem to work... At a glance.
– Hitch Leonardo
Yes, because it is in the wrong place. The two dots should be added right after setting the variable
leg
. And this, inside theif
that checks whether the route worked.– Paulo Rodrigues
Yes. I edited the script and now it works. The problem is that it is still showing that initial Marketer that is preset when the user views the map before setting the route. How do I remove it?
– Hitch Leonardo
marker.setMap(null)
– Paulo Rodrigues
It worked, but my infowindow, disappeared.... As a return it to appear in "Leg.end_location"?
– Hitch Leonardo
Leonardo, you need to read more the documentation, it’s all there in a very simple way. What you have done around here is question upon question and filling up the area that would be for comments and without researching at all, making it very broad. Read also how to ask a good question that can help you get along right here on Stack Overflow. For example, about this doubt you find easily here.
– Paulo Rodrigues
Paulo Rodrigues, in no way game questions. Stackoverflow is a community for questions and questions, especially for beginners. I deeply appreciate your help, I am a layman at API, and I am learning little by little, I see people here as tutors, I stay up at dawn and dawn trying to get the best result. I can’t always understand. Thank you very much for your help and consideration. Hugs
– Hitch Leonardo