javascript directions with google maps - javascript

how can i change the start = $("#from").val();, value option, to users current position? It's more comfortable without typing the start adress.
Any help?
<script type="text/javascript">
$(document).on("pageinit", "#map_page", function() {
initialize();
});
$(document).on('click', '#submit', function(e) {
e.preventDefault();
calculateRoute();
});
var directionDisplay,
directionsService = new google.maps.DirectionsService(),
map;
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
var mapCenter = new google.maps.LatLng(51.507009, -0.170720);
var myOptions = {
zoom:16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mapCenter
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directions"));
}
function calculateRoute()
{
var selectedMode = $("#mode").val(),
start = $("#from").val();,
end = new google.maps.LatLng(51.507009, -0.170720);
//start = $("#from").val();
if(start == '' || end == '')
{
// cannot calculate route
$("#results").hide();
return;
}
else
{
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
$("#results").show();
/*
var myRoute = response.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
alert(myRoute.steps[i].instructions);
}
*/
}
else {
$("#results").hide();
}
});
}
}
</script>

The solution is to use https and not http for getCurrentPosition() and watchPosition()

Related

set google origin search box address with a variable

I'm trying to make origin SearchBox destination be string with legit direction, but when I do so I still need to select the first option for it to work (to calculate distance).
Got the this searching around to calculate distance between 2 points and it works perfectly:
How can I add multiple searchBoxes in my google maps api web?
I got a string for example :albrook mall which i know exist( this string is dynamic is coming from a variable and all address are validated. get the needed address pass it to a variable so I can read it on the frontEnd, and set the value of search box in the html. the value is updated with jquery
But what happens is that I still have to click on the origin search box then this list all possible locations which in my case is the first one, how can I make the map either auto select the first option or recognize the address that is set in the input value?
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 9.0271554,
lng: 79.4816371
},
zoom: 15
});
var marker = new google.maps.Marker({
map: map,
draggable: false
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
/*marker.setPosition(initialLocation); */
});
}
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
this.avoidTolls = true;
this.avoidHighways= true;
//this.provideRouteAlternatives= true,
this.avoidFerries= true;
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
this.directionsRenderer.setMap(map);
var originInput = document.getElementById('orign');
var destinationInput = document.getElementById('destn');
var originAutocomplete = new google.maps.places.SearchBox(originInput);
var destinationAutocomplete =
new google.maps.places.SearchBox(destinationInput);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('places_changed', function() {
var places = autocomplete.getPlaces();
var place = places[0];
if (!place.place_id) {
window.alert('Please select an option from the dropdown list.');
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode,
avoidTolls: this.avoidTolls
},
function(response, status) {
if (status === 'OK') {
me.directionsRenderer.setDirections(response);
computeTotalDistance(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
// from Google Maps API: Total distance with waypoints
// https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
time = (totalTime / 60).toFixed(2)
document.getElementById("totalkm").innerHTML ="" + totalDist + "km" ;
document.getElementById("totaltime").innerHTML ="" + time + " minutos";
if(totalDist <= 5){
document.getElementById("totalCost").innerHTML =" $3.50";
}
else{
kmPrice = (totalDist - 5) * 0.75;
document.getElementById("totalCost").innerHTML ="$" +(kmPrice + 3.50).toFixed(2)+ "";
}
}
function send_handle(){
let name=document.getElementById("name").value;
///let lastname= document.getElementById("lastname").value;
let inst= document.getElementById("instructions").value;
let origin= document.querySelector(".selectButtons input#orign").value;
let destination= document.querySelector(".selectButtons input#destn").value;
let cost= document.getElementById("totalCost").innerHTML;
let distance= document.getElementById("totalkm").innerHTML;
// win.focus();
}
</script>
<html>
<div class="selectButtons" >
<input type="text" id="orign" placeholder="origen">
<input type="text" id="destn" placeholder="destino">
<span> Distancia en KM <div id="totalkm">0km</div> </span>
<span> Distancia en tiempo <div id="totaltime">o.oo</div> </span>
<span> costo por envio<div id="totalCost">$0</div></div> </span>
</div>
</html>
You can call the places service to get the PlaceId (with your string), then pass that placeId into the constructor for your AutocompleteDirectionsHandler or if you already have the PlaceId (you are allowed to store those), just use it, although you probably want to initialize the origin input with the string.
var origin = "Allbrook, Panama";
var originInput = document.getElementById('orign');
originInput.value = origin;
const request = {
query: origin,
fields: ["name", "geometry", "place_id"],
};
var originPlaceId;
var service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK && results) {
originPlaceId = results[0].place_id;
console.log("placeId="+originPlaceId+" coords="+results[0].geometry.location.toUrlValue(6));
new AutocompleteDirectionsHandler(map, originPlaceId);
map.setCenter(results[0].geometry.location);
}
});
Add the initial origin placeId to the AutocompleteDirectionsHandler constructor:
function AutocompleteDirectionsHandler(map, originPlaceId) {
this.map = map;
this.originPlaceId = originPlaceId;
// ...
on load:
after selecting destination from dropdown:
code snippet:
let map;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 9.0271554,
lng: 79.4816371
},
zoom: 15
});
var origin = "Allbrook, Panama";
var originInput = document.getElementById('orign');
originInput.value = origin;
const request = {
query: origin,
fields: ["name", "geometry", "place_id"],
};
var originPlaceId;
var service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK && results) {
originPlaceId = results[0].place_id;
console.log("placeId="+originPlaceId+" coords="+results[0].geometry.location.toUrlValue(6));
new AutocompleteDirectionsHandler(map, originPlaceId);
map.setCenter(results[0].geometry.location);
}
});
var marker = new google.maps.Marker({
map: map,
draggable: false
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
/*marker.setPosition(initialLocation); */
});
}
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map, originPlaceId) {
this.map = map;
this.originPlaceId = originPlaceId;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
this.avoidTolls = true;
this.avoidHighways = true;
//this.provideRouteAlternatives= true,
this.avoidFerries = true;
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
this.directionsRenderer.setMap(map);
var originInput = document.getElementById('orign');
var destinationInput = document.getElementById('destn');
var originAutocomplete = new google.maps.places.SearchBox(originInput);
var destinationAutocomplete =
new google.maps.places.SearchBox(destinationInput);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('places_changed', function() {
var places = autocomplete.getPlaces();
var place = places[0];
if (!place.place_id) {
window.alert('Please select an option from the dropdown list.');
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode,
avoidTolls: this.avoidTolls
},
function(response, status) {
if (status === 'OK') {
me.directionsRenderer.setDirections(response);
computeTotalDistance(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
// from Google Maps API: Total distance with waypoints
// https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
time = (totalTime / 60).toFixed(2)
document.getElementById("totalkm").innerHTML = "" + totalDist + "km";
document.getElementById("totaltime").innerHTML = "" + time + " minutos";
if (totalDist <= 5) {
document.getElementById("totalCost").innerHTML = " $3.50";
} else {
kmPrice = (totalDist - 5) * 0.75;
document.getElementById("totalCost").innerHTML = "$" + (kmPrice + 3.50).toFixed(2) + "";
}
}
function send_handle() {
let name = document.getElementById("name").value;
///let lastname= document.getElementById("lastname").value;
let inst = document.getElementById("instructions").value;
let origin = document.querySelector(".selectButtons input#orign").value;
let destination = document.querySelector(".selectButtons input#destn").value;
let cost = document.getElementById("totalCost").innerHTML;
let distance = document.getElementById("totalkm").innerHTML;
// win.focus();
}
function createMarker(place) {
if (!place.geometry || !place.geometry.location) return;
const marker = new google.maps.Marker({
map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, "click", () => {
infowindow.setContent(place.name || "");
infowindow.open(map);
});
}
window.initMap = initMap;
#map-canvas {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<html>
<div class="selectButtons">
<input type="text" id="orign" placeholder="origen" />
<input type="text" id="destn" placeholder="destino" />
<span> Distancia en KM <div id="totalkm">0km</div> </span>
<span> Distancia en tiempo <div id="totaltime">o.oo</div> </span>
<span> costo por envio<div id="totalCost">$0</div> </span>
</div>
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>
</html>

Google Maps API - Markers to Directions Route Service

I am trying to add additional markers (custom icons) to my directional Google maps, but I cant seem to add these outside the initialize() function.
I need to add them outside the initialize() function, because I would like to icons to change based on the route. It's the ADD EXTRA MARKERS TEST which I'm having trouble with. All the rest of the script works perfectly.
Many thanks in advance for any help.
Code so far:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var stepDisplay;
function initialize() {
var latlng = new google.maps.LatLng( <? echo $lat; ?> , <? echo $lon; ?> );
var rendererOptions = {draggable: true};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var myOptions = {zoom: 14,center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP,mapTypeControl: false};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
//calcRoute
function calcRoute() {
var travelMode = 'DRIVING';
var start = $("#routeStart").val();
var via = $("#routeVia2").val();
var end = $("#routeVia").val();
var waypoints = [];
if (via != '') {waypoints.push({location: via,stopover: true});
}
var request = {
origin: start,
destination: end,
waypoints: waypoints,
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: google.maps.DirectionsTravelMode[travelMode]
};
//DISPLAY ROUTE AND PASS LATLNG TO PHP FILE FOR FURTHER PROCESSING
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myRoute = response.routes[0];
var txtDir = '';
for (var i=0; i<myRoute.legs[0].steps.length; i++) {
txtDir += myRoute.legs[0].steps[i].path+"";
}
var strLAT = "" + txtDir;
//SEND DATA TO URL PHP FILE
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}}
xmlHttp.open("POST",'MYPHPFILE',true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("LATLON="+strLAT);
//ALERT TEST TO ENSURE PHP PROCESSED DATA CORRECTLY
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
alert($('#ResponseDiv').text());
}
ADD EXTRA MARKERS TEST
var wxlatlng = new google.maps.LatLng( 52 , -1 );
var marker = new google.maps.Marker({
position: wxlatlng,
map: map,
icon: "http://nwsgeo.com/demo/images/pins/road-closed.jpg",
title: "test icon",
});
//ERROR MESSAGES
}else{
if (status == 'ZERO_RESULTS') {
alert('No route could be found between the origin and destination.');
}else if(status == 'INVALID_REQUEST') {
alert('The DirectionsRequest provided was invalid.');
}else{
alert("There was an unknown error in your request. Requeststatus: nn" + status);
}}});}

directionsService.route does not return data to bind div

I am doing some js to get directions panel with asp.net
<!-- language: lang-js -->
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
function calcRoute(lat,lan) {
var InitialOrigin = document.getElementById('ctl00_ContentPlaceHolder1_FESearchListingControl1_txtHide').value;
//var InitialOrigin = document.getElementById("txtHide").Value;
var technopark = new google.maps.LatLng(8.5572357 ,76.87649310000006 );
var split = InitialOrigin.split(',');
var latFrom = parseFloat(split[0]);
var lanFrom = parseFloat(split[1]);
InitialOrigin= new google.maps.LatLng(latFrom,lanFrom);
var to = new google.maps.LatLng(lat,lan);
// var start = document.getElementById("start").value;
// var end = document.getElementById("end").value;
var request = {
origin:InitialOrigin,
destination:to,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
else
{
console.log('something went wrong',status);
}
});
}
I debugged with crome browser and could find that the the line
directionsService.route(request, function(response, status) {
did not return anything,the debugger just jumped to the last closing brace.
The debugger never entered this if statement
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
else
{
console.log('something went wrong',status);
}
This was working before,and i was getting the directions panel before,is there some restrictions with google ?

for each only running once

First let me explain. I have several addresses on the page that I put into an array. I then want to go over that array and replace each address with its longitude and latitude.
The problem is my attempt only runs one time.
$(function () {
var addr = 0;
var shops = [];
var addressPoint;
var latlng = new google.maps.LatLng(38, -97);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
window.onload = function () {
var options = [];
$('.address').each(function () {
if (!$(this).is(":empty")) {
options.push($(this).text());
txt = $(this).text();
} else {}
});
alert(options);
$.each(options, function () {
var addr = ("'" + this + "'");
searchAddr(addr);
});
function searchAddr(addr) {
$('#map_canvas').gmap({
'callback': function () {
var self = this;
alert(addr);
self.search({
'address': addr
}, function (results, status) {
if (status === 'OK') {
addressPoint = results[0].geometry.location;
alert(addressPoint);
options = $.map(options, function () {
return results[0].geometry.location;
});
self.get('map').panTo(results[0].geometry.location);
alert(options);
return false;
}
});
}
});
}
};
}(jQuery));
Did you use a network sniffer to confirm it is only firing once? Because it looks like you are replacing each value in the list with a single value in the $.map command. Perhaps if you put the address points in a different array it would help:
$(function () {
var addr = 0;
var shops = [];
var addressPoint;
var latlng = new google.maps.LatLng(38, -97);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var points = [];
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
window.onload = function () {
var options = [];
$('.address').each(function () {
if (!$(this).is(":empty")) {
options.push($(this).text());
txt = $(this).text();
} else {}
});
alert(options);
$.each(options, function () {
var addr = ("'" + this + "'");
searchAddr(addr);
});
function searchAddr(addr) {
$('#map_canvas').gmap({
'callback': function () {
var self = this;
alert(addr);
self.search({
'address': addr
}, function (results, status) {
if (status === 'OK') {
addressPoint = results[0].geometry.location;
alert(addressPoint);
points.push(addressPoint);
});
self.get('map').panTo(addressPoint);
alert(points);
return false;
}
});
}
});
}
};
}(jQuery));

How can I timeout a google maps geocoder via javascript?

I am very new to javascript and I am having issues with timing out the geocoder requests.
But I am stuck, I tries to add delays into loop, but seems like they don't work.
If you can help, I would appreciarte it.
<script type="text/javascript">
function setLocationOnMap(locs) {
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(locs.lat(), locs.lng()),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var i=0;
var total='<?php echo $counter ?>';
for (i=0; i<total;i++){//adding cities to map by
var city= document.the_form.elements[i].value;
getLatLong2(city, map, setPointer);
}
}
function setPointer(map, address, locs2){
var position = new google.maps.LatLng(locs2.lat(), locs2.lng());
var marker = new google.maps.Marker({
position: position,
map: map
});
marker.setTitle(address);
}
function initialize() {
var address = "Chicago IL";
getLatLong(address, setLocationOnMap);
}
function getLatLong2(address, map, callback){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
locs2 = results[0].geometry.location;
callback(map, address, locs2);
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
function getLatLong(address, callback){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
// processing...
locs = results[0].geometry.location;
//pausecomp(10000);
callback(locs);
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
When you submit the geocode request, you can start a timer in parallel and when the timer fires, you can declare the request to have timed out. The request will still continue, but you can ignore the results once it has timed out:
function getLatLong(address, callback){
var timerId;
var timedOut = false;
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (timedOut) {
// this request timed out, so ignore results
return;
} else {
// this request succeeded, so cancel timer
clearTimeout(timerId);
}
if (status == google.maps.GeocoderStatus.OK) {
locs = results[0].geometry.location;
callback(locs);
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
timerId = setTimeout(function() {
timedOut = true;
alert('Request timed out.');
// do something else
}, 10000);
}

Categories