calculate distance before submitting form - javascript

I am trying to calculate a distance from my workplace to a destination that varies.
I have a form with 3 fields:
date
destination
distance
I would like get the distance by just typing in the destination address - this should happen before I submit the form (for best user experience).
I am trying to use google maps api but can't get the input in the destination field into the js code var DestinationA. I am also using the "onchange" to get the inout before submitting.
My next step is then to get the distance result into the form field distance.
Any help is much appreciated.
Here is my test-site: www.e-kl.dk/s/_kort.asp
Here is my code:
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 200px;
width: 200px;
position: absolute;
left: 3px;
top: 92px;
z-index: 1;
}
#content-pane {
float:right;
width:48%;
padding-left: 2%;
}
#outputDiv {
font-size: 11px;
height: 50px;
width: 876px;
position: absolute;
left: 0px;
}
</style>
</head>
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = 'Gl. Hovedgade 10, Denmark';
// var destinationA = 'ballerup'; //THIS WORKS but I need the user input....
// var destinationA = document.form1.destination; //did not work
// var addressField = document.getElementById('destination'); //did not work
// var destinationA = addressField.value;
// var destinationA = $("#destination").val(); //did not work
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.876, 12.5),
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'), opts);
geocoder = new google.maps.Geocoder();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1],
destinations: [destinationA],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += 'Tegnestuen' + ' til ' + destinations[j]
+ ': ' + results[j].distance.text;
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="outputDiv">
<form id="form1" name="form1" method="post" action="">
date
<input name="date" type="text" value="" id="date"/>
destination
<input name="destination" type="text" value="" id="destination" onchange="calculateDistances();"/>
distance
<input name="distance" type="text" value="" id="distance" />
</form>
</div>
<div id="map-canvas"></div>
</body>
</html>

You can't access document.getElementById('destination') until the onload event has fired. Best to get that value in the calculateDistances function (when it is needed):
function calculateDistances() {
var addressField = document.getElementById('destination'); //did not work
var destinationA = addressField.value;
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationA],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
working fiddle

Related

Rendering routes with GoogleAPI JS

I was following along with a tutorial involving the GoogleMaps API JS, and everything went well. When trying to building my own app I've come across an issue with displaying a route. The application I'm working on is mainly written in ruby on rails.
The "pseudo code" problem is when clicking on to "view route" button, the route is not displaying on the map.
Below is the HTML that triggers the first event when clicking on the search with in time button, and the CSS as requested.
<body>
<div>
<span class="text"> Within </span>
<select id='max-duration'>
<option value="10">10 min</option>
</select>
<select id="mode">
<option value="DRIVING">drive</option>
</select>
<span class="text">of</span>
<input id= 'search-within-time-text' type='text' placeholder='Your Location'>
<input id= 'search-within-time' type='button' value='Go'>
</div>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places,drawing,geometry&key=<%= ENV["MAP_API"] %>&v=3"></script>
</body>
<style>
#map {
bottom: 0px;
height: 500px;
left: 362px;
position: absolute;
right: 0px;
}
.container {
height: 500px;
position: relative;
}
.options-box {
background: #fff;
border: 1px solid black;
height: 91.75%;
line-height: 35px;
padding: 10px 10px 30px 10px;
text-align: left;
width: 340px;
}
#zoom-to-area-text{
width:200px;
}
</style>
The location array that is stroing the data is found in the maps controller, where we are pushing data from our SQLite DB.
def index
#test_array = []
#test.each do |h|
#test_array.push({lat: h.lat, lng: h.lng})
end
end
In particular I believe the problem lays within the function displayDirections. Which can be found at the bottom of the full code
The displayDirections function is written outside of the initMap function, because of a scoping issue when it is written inside of the initMap function. I've read the problem below
Maybe a similar issue
But had issues with displayDirections being defined at the click event, when it was written with in the initMap function, in the function displayMarkersWithinTime.
Any help is appreciated! Thanks!
function initMap() {
var map;
var markers = [];
var placeMarkers = [];
document.getElementById('search-within-time').addEventListener('click', function(){
searchWithinTime();
});
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.9523789, lng: -75.1635996},
zoom: 13,
mapTypeControl: false
});
var locations = <%= raw #test_array.to_json%>
for (var i = 0; i < locations.length; i++) {
var position = locations[i]
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.DROP,
id: i
});
markers.push(marker);
}
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++){
markers[i].setMap(null);
}
}
function searchWithinTime(){
var distanceMatrixService = new google.maps.DistanceMatrixService;
var address = document.getElementById('search-within-time-text').value;
if (address == ''){
window.alert('You must enter an address.');
} else {
hideMarkers(markers);
var origins = [];
for (var i = 0; i < markers.length; i++) {
origins[i] = markers[i].position;
}
var destination = address;
var mode = document.getElementById('mode').value;
distanceMatrixService.getDistanceMatrix({
origins: origins,
destinations: [destination],
travelMode: google.maps.TravelMode[mode],
unitSystem: google.maps.UnitSystem.IMPERIAL,
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
window.alert('Error was: ' + status);
} else {
displayMarkersWithinTime(response);
}
});
}
}
function displayMarkersWithinTime(response){
var maxDuration = document.getElementById('max-duration').value;
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var atLeastOne = false;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
if (element.status === "OK") {
var distanceText = element.distance.text;
var duration = element.duration.value / 60;
var durationText = element.duration.text;
if (duration <= maxDuration) {
markers[i].setMap(map);
atLeastOne = true;
var infowindow = new google.maps.InfoWindow({
content : durationText + ' away, ' + distanceText + '<div><input type=\"button\" value=\"View Route\" onclick =' + '\"displayDirections("' + origins[i] + '");\"</input></div>'
});
infowindow.open(map, markers[i]);
// if user clicks on marker close the small info window to open a new
markers[i].infowindow = infowindow;
google.maps.event.addListener(markers[i], 'click', function (){
this.infowindow.close();
});
}
}
}
}
if(!atLeastOne) {
window.alert('We could not find any locations within that distance');
}
console.log("hello")
}
}
var map;
var markers = [];
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.9523789, lng: -75.1635996},
zoom: 13,
mapTypeControl: false
});
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++){
markers[i].setMap(null);
}
}
function displayDirections(origin) {
hideMarkers(markers);
var directionsService = new google.maps.DirectionsService;
var destinationAddress = document.getElementById('search-within-time-text').value;
var mode = document.getElementById('mode').value;
directionsService.route({
origin: origin,
destination: destinationAddress,
travelMode: google.maps.TravelMode[mode]
}, function(response, status) {
console.log(response)
console.log(status)
if (status === google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
draggable: true,
polylineOptions: {
strokeColor: 'black'
}
}, console.log(map), console.log(response));
} else {
window.alert('Directions request failed due to ' + status);
}
});
console.log("testing")
}
google.maps.event.addDomListener(window, initMap())
Your (initialized) map variable is local to the initMap function. Make it global.
Change:
function initMap() {
var map;
// ...
To:
var map;
function initMap() {
proof of concept fiddle
code snippet:
var map;
function initMap() {
var markers = [];
var placeMarkers = [];
var titles;
var latitudes;
var longitudes;
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
document.getElementById('show-listings').addEventListener('click', showListings);
document.getElementById('hide-listings').addEventListener('click', function() {
hideMarkers(markers);
});
document.getElementById('search-within-time').addEventListener('click', function() {
searchWithinTime();
});
var timeAutocomplete = new google.maps.places.Autocomplete(
document.getElementById('search-within-time-text'));
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 39.9523789,
lng: -75.1635996
},
zoom: 13,
mapTypeControl: false
});
var locations = [{
lat: 39.952584,
lng: -75.165222
}, {
lat: 47.6062095,
lng: -122.3320708
},
{
lat: 34.0522342,
lng: -118.2436849
},
{
lat: 39.114053,
lng: -94.6274636
}, {
lat: 25.7616798,
lng: -80.1917902
}
];
for (var i = 0; i < locations.length; i++) {
var position = locations[i]
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.DROP,
id: i,
map: map
});
markers.push(marker);
}
function showListings() {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
bounds.extend(markers[i].position);
}
map.fitBounds(bounds);
}
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
function searchWithinTime() {
var distanceMatrixService = new google.maps.DistanceMatrixService();
var address = document.getElementById('search-within-time-text').value;
if (address == '') {
window.alert('You must enter an address.');
} else {
hideMarkers(markers);
var origins = [];
for (var i = 0; i < markers.length; i++) {
origins[i] = markers[i].position;
}
var destination = address;
var mode = document.getElementById('mode').value;
distanceMatrixService.getDistanceMatrix({
origins: origins,
destinations: [destination],
travelMode: google.maps.TravelMode[mode],
unitSystem: google.maps.UnitSystem.IMPERIAL,
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
window.alert('Error was: ' + status);
} else {
displayMarkersWithinTime(response);
}
});
}
}
function displayMarkersWithinTime(response) {
var maxDuration = document.getElementById('max-duration').value;
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var atLeastOne = false;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
if (element.status === "OK") {
var distanceText = element.distance.text;
var duration = element.duration.value / 60;
var durationText = element.duration.text;
if (duration <= maxDuration) {
markers[i].setMap(map);
atLeastOne = true;
var infowindow = new google.maps.InfoWindow({
content: durationText + ' away, ' + distanceText + '<div><input type=\"button\" value=\"View Route\" onclick =' + '\"displayDirections("' + origins[i] + '");\"</input></div>'
});
infowindow.open(map, markers[i]);
// if user clicks on marker close the small info window to open a new
markers[i].infowindow = infowindow;
google.maps.event.addListener(markers[i], 'click', function() {
this.infowindow.close();
});
}
}
}
}
if (!atLeastOne) {
window.alert('We could not find any locations within that distance');
}
console.log("hello")
}
}
var map;
var markers = [];
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 39.9523789,
lng: -75.1635996
},
zoom: 13,
mapTypeControl: false
});
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
function displayDirections(origin) {
hideMarkers(markers);
var directionsService = new google.maps.DirectionsService();
var destinationAddress = document.getElementById('search-within-time-text').value;
var mode = document.getElementById('mode').value;
directionsService.route({
origin: origin,
destination: destinationAddress,
travelMode: google.maps.TravelMode[mode]
}, function(response, status) {
console.log(response)
console.log(status)
if (status === google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
draggable: true,
polylineOptions: {
strokeColor: 'black'
}
}, console.log(map), console.log(response));
} else {
window.alert('Directions request failed due to ' + status);
}
});
console.log("testing")
}
google.maps.event.addDomListener(window, 'load', initMap)
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
background-color: white;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" value="search" id="search-within-time" />
<input type="text" value="coffee" id="search-within-time-text" />
<input type="button" value="Show" id="show-listings" />
<input type="button" value="Hide" id="hide-listings" />
<input type="text" value="DRIVING" id="mode" />
<input type="text" value="1200" id="max-duration" />
<div id="map"></div>

How to get Sorted alphabetical markers

The code in the fiddle below has 3 Fixed Locations. An address can then be inputted and the distance from that address to all three Fixed Locations will be calculated. The results are then sorted in order by distance in a sidebar on the right.
I'm trying to figure out how to assign lettered markers for each result. So each time the results are calculated, the first closest marker would be letter A, the second closest marker would be letter B and so on. I'd also like the letter A to appear in the sidebar next to the first closest result and letter B to appear in the sidebar next to the second closest results and so on.
I haven't been able to find any instructions how to do this? Can anyone help?
Thanks
http://jsfiddle.net/geocodezip/vj0cpv0c/2/
var locations = [
["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],
What you where looking for was .set('label', letterMarkers); using int to char we can turn 0 into A, 1 into B and place this onto the markers and list.
in function calculateDistances you work out and sort the pins, which we can then draw the letters on, I also added the letter above the link in the right list
you should now see a,b,c in the list on the right
and pins in a,b,c order from distance
code changed:
closest[i].setMap(map);
var letterMarkers = String.fromCharCode(97 + i);
closest[i].set('label', letterMarkers);
outputDiv.innerHTML += letterMarkers + " <br>
all code:
var locations = [
["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],
];
// alert(locations.length);
var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
// alert("init");
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(52.6699927, -0.7274620),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
document.getElementById('info').innerHTML = "found " + locations.length + " locations<br>";
for (i = 0; i < locations.length; i++) {
var coordStr = locations[i][2];
var coords = coordStr.split(",");
var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
bounds.extend(pt);
marker = new google.maps.Marker({
position: pt,
map: map,
icon: locations[i][3],
address: locations[i][1],
title: locations[i][0],
html: locations[i][0] + "<br>" + locations[i][1] + "<br><br><a href='javascript:getDirections(customerMarker.getPosition(),"" + locations[i][1] + "");'>Get Directions</a>"
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})
(marker, i));
}
map.fitBounds(bounds);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (customerMarker) customerMarker.setMap(null);
customerMarker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
closest = findClosestN(results[0].geometry.location, 12);
// get driving distance
closest = closest.splice(0, 12);
calculateDistances(results[0].geometry.location, closest, 12);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function findClosestN(pt, numberOfResults) {
var closest = [];
document.getElementById('info').innerHTML += "processing " + gmarkers.length + "<br>";
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gmarkers[i].getPosition());
document.getElementById('info').innerHTML += "process " + i + ":" + gmarkers[i].getPosition().toUrlValue(6) + ":" + gmarkers[i].distance.toFixed(2) + "<br>";
gmarkers[i].setMap(null);
closest.push(gmarkers[i]);
closest.sort(sortByDist);
}
return closest;
}
function sortByDist(a, b) {
return (a.distance - b.distance)
}
function calculateDistances(pt, closest, numberOfResults) {
var service = new google.maps.DistanceMatrixService();
var request = {
origins: [pt],
destinations: [],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
};
for (var i = 0; i < closest.length; i++) {
request.destinations.push(closest[i].getPosition());
}
service.getDistanceMatrix(request, function(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('side_bar');
outputDiv.innerHTML = '';
var results = response.rows[0].elements;
// save title and address in record for sorting
for (var i = 0; i < closest.length; i++) {
results[i].title = closest[i].title;
results[i].address = closest[i].address;
results[i].idx_closestMark = i;
}
results.sort(sortByDistDM);
for (var i = 0;
((i < numberOfResults) && (i < closest.length)); i++) {
closest[i].setMap(map);
var letterMarkers = String.fromCharCode(97 + i);
closest[i].set('label', letterMarkers);
outputDiv.innerHTML += letterMarkers + " <br><a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),"" + results[i].address + "");'>Get Directions</a><br><hr>"
}
}
});
}
function getDirections(origin, destination) {
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
directionsDisplay.setPanel(document.getElementById('side_bar'));
}
});
}
function sortByDistDM(a, b) {
return (a.distance.value - b.distance.value)
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
table,tr,td {
height: 100%;
}
.text {
width: 300px;
height: 600px;
background-color: white;
overflow: scroll;
overflow-x: hidden;
}
<table border="0">
<tr>
<td>
<div id="map" style="height: 100%; width:400px;"></div>
</td>
<td>
<div id="side_bar" class='text'> </div>
</td>
</tr>
</table>
<input id="address" type="text" value="Paramus, NJ" />
<input type="button" value="Search" onclick="codeAddress();" />
<div id="info"></div>
To follow up,sorted pins I used general javascript to make closest match results, there may be a better way of doing this with the API.
added code:
var pins = [];
results.forEach(function(result){
closest.forEach(function (addr){
if(result.address === addr.address){
pins.push(addr);
}
});
});
and used pins[i] instead of closest in the for loop.
all code:
var locations = [
["John Doe", "29 Buhl Lane, East Northport, NY ", "40.858924, -73.297327", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],
];
// alert(locations.length);
var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
// alert("init");
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(52.6699927, -0.7274620),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
document.getElementById('info').innerHTML = "found " + locations.length + " locations<br>";
for (i = 0; i < locations.length; i++) {
var coordStr = locations[i][2];
var coords = coordStr.split(",");
var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
bounds.extend(pt);
marker = new google.maps.Marker({
position: pt,
map: map,
icon: locations[i][3],
address: locations[i][1],
title: locations[i][0],
html: locations[i][0] + "<br>" + locations[i][1] + "<br><br><a href='javascript:getDirections(customerMarker.getPosition(),"" + locations[i][1] + "");'>Get Directions</a>"
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})
(marker, i));
}
map.fitBounds(bounds);
$("#mdiv").click(function() {
$("#side_bar").css({
"z-index": 100,
"top": "0px"
});
$("#panel").css("z-index", -100);
$("#mdiv").css("display", "none");
})
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (customerMarker) customerMarker.setMap(null);
customerMarker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
closest = findClosestN(results[0].geometry.location, 12);
// get driving distance
closest = closest.splice(0, 12);
calculateDistances(results[0].geometry.location, closest, 12);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function findClosestN(pt, numberOfResults) {
var closest = [];
document.getElementById('info').innerHTML += "processing " + gmarkers.length + "<br>";
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gmarkers[i].getPosition());
document.getElementById('info').innerHTML += "process " + i + ":" + gmarkers[i].getPosition().toUrlValue(6) + ":" + gmarkers[i].distance.toFixed(2) + "<br>";
gmarkers[i].setMap(null);
closest.push(gmarkers[i]);
closest.sort(sortByDist);
}
return closest;
}
function sortByDist(a, b) {
return (a.distance - b.distance)
}
function calculateDistances(pt, closest, numberOfResults) {
var service = new google.maps.DistanceMatrixService();
var request = {
origins: [pt],
destinations: [],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
};
for (var i = 0; i < closest.length; i++) {
request.destinations.push(closest[i].getPosition());
}
service.getDistanceMatrix(request, function(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('side_bar');
outputDiv.innerHTML = '';
var results = response.rows[0].elements;
// save title and address in record for sorting
for (var i = 0; i < closest.length; i++) {
results[i].title = closest[i].title;
results[i].address = closest[i].address;
results[i].idx_closestMark = i;
}
results.sort(sortByDistDM);
var pins = [];
results.forEach(function(result){
closest.forEach(function (addr){
if(result.address === addr.address){
pins.push(addr);
}
});
});
for (var i = 0;
((i < numberOfResults) && (i < closest.length)); i++) {
pins[i].setMap(map);
var letterMarkers = String.fromCharCode(97 + i);
pins[i].set('label', letterMarkers);
outputDiv.innerHTML += letterMarkers + " <br><a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),"" + results[i].address + "");'>Get Directions</a><br><hr>"
}
}
});
}
function getDirections(origin, destination) {
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
$("#side_bar").css({
"z-index": -100,
"top": "25px"
});
$("#panel").css("z-index", 100);
$("#mdiv").css("display", "block");
directionsDisplay.setPanel(document.getElementById('panel'));
}
});
}
function sortByDistDM(a, b) {
return (a.distance.value - b.distance.value)
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
margin: 0;
padding: 0;
height: 600px;
width: 400px;
}
.text {
width: 300px;
height: 600px;
background-color: white;
overflow: scroll;
overflow-y: auto;
overflow-x: hidden;
}
#side_bar {
z-index: 100;
position: absolute;
top: 135px;
left: 400px;
}
#panel {
z-index: -100;
display: block;
position: absolute;
top: 135px;
left: 400px;
}
#mdiv {
z-index: 500;
width: 25px;
height: 25px;
display: none;
background-color: red;
border: 1px solid black;
position: absolute;
left: 660px;
top: 112px;
}
.mdiv {
height: 25px;
width: 2px;
margin-left: 12px;
background-color: black;
transform: rotate(45deg);
-ms-transform: rotate(45deg);
/* IE 9 */
-webkit-transform: rotate(45deg);
/* Safari and Chrome */
z-index: 1;
}
.md {
height: 25px;
width: 2px;
background-color: black;
transform: rotate(90deg);
-ms-transform: rotate(90deg);
/* IE 9 */
-webkit-transform: rotate(90deg);
/* Safari and Chrome */
z-index: 2;
}
tr:nth-child(even) {
background: #CCC
}
tr:nth-child(odd) {
background: #FFF
}
<div class="bh-sl-container">
<div id="page-header">
<h1 class="bh-sl-title">The Auditor Locator</h1>
</div>
<div class="bh-sl-form-container">
<form id="bh-sl-user-location" method="post" action="#">
<div class="form-input">
<label for="bh-sl-address">Enter Address or Zip Code:</label>
<input id="address" type="text" value="Danbury, CT" />
<input type="button" value="Submit" onclick="codeAddress();" />
</div>
</form>
</div>
<table border="0" style="height:100%">
<tr style="height:100%">
<td style="height:100%">
<div id="map"></div>
</td>
<td>
<div id="side_bar" class='text'></div>
<div id="panel" class='text'></div>
</td>
</tr>
</table>
<div id="info"></div>
<div id="mdiv">
<div class="mdiv">
<div class="md">
</div>
</div>
</div>

How to get all latitudes and longitudes from source place to destination place

I want to get all the latitudes and longitudes from google map.
For Example : suppose i have enter lat and lon of source and destination and the path is drawn on the map as below:
so now i want all the lat and lon between this A source and B destination. and that all lat and lon have to store in the database.
so when i track my car and that car are not moving on this path/way then at that it will fire some action like send me email etc.
i am developing with asp.net c#.
so how can i get the all the lat and lon ?
i am using below script
<script>
function initialize() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 8,
center: new google.maps.LatLng(22.304634, 73.161070),
mapTypeId: google.maps.MapTypeId.ROADMAP
}),
directions = new google.maps.DirectionsService(),
displayer = new google.maps.DirectionsRenderer({
draggable: true
});
displayer.setMap(map);
directions.route({
origin: new google.maps.LatLng(22.304634, 73.161070),
destination: new google.maps.LatLng(23.022242, 72.548844),
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result) {
displayer.setDirections(result);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(displayer, 'directions_changed', some_method);
</script>
You have to loop over the overview_path property of the google.maps.DirectionsRoute object. Then create your object (or just serialize overview_path) to send it to the server and stock it in the data base.
Chek out this example for how to loop over the overview_path:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<style>
html, body, #map-canvas { height: 100%; min-height: 600px; min-width: 700px; margin: 0px; padding: 0px }
#map-canvas { height: 50%; }
#panel { position: absolute; top: 5px; left: 50%; margin-left: -180px; z-index: 5; background-color: #fff; padding: 5px; border: 1px solid #999; }
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
</head>
<body>
<div id="panel">
<label>Origin
<input id="origin" type="text" value="">
</label>
<label>Destination
<input id="destination" type="text" value="">
</label>
<input type="button" value="GetDirections" onclick="calcRoute()">
</div>
<div id="map-canvas"></div>
<div id="vertex-container">
<label>Points</label>
<ul id="vertex">
</ul>
</div>
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(48.85727000, 2.35238)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('origin').value;
var end = document.getElementById('destination').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
if (response.routes && response.routes.length > 0) {
var routes = response.routes;
for (var j = 0; j < routes.length; j++) {
var points = routes[j].overview_path;
var ul = document.getElementById("vertex");
for (var i = 0; i < points.length; i++) {
var li = document.createElement('li');
li.innerHTML = getLiText(points[i]);
ul.appendChild(li);
}
}
}
}
});
}
function getLiText(point) {
var lat = point.lat(),
lng = point.lng();
return "lat: " + lat + " lng: " + lng;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>

Get Markers Addresses in Input fields using Drag-able Google Maps API V3

I am using Google Maps API V3 drag-able markers with auto-suggest in FROM and TO Field. After Clicking Show Route I get Map with 2 Markers A and B. If I change Marker A or B it Shows Updated Location in Navigation (directionsPanel). I need These Locations in FROM NEW MARKER ADDRESS: And TO NEW MARKER ADDRESS: Input fields when markers A and B dragged.A is for FROM and B is for TO Location. I searched on google and read API Details but did not find a solution. I need to insert these updated marker location (addresses) in Database for future references. Thanks in Advance.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Map Finalized</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#directionsPanel{
overflow-y:auto;
width:40%;
height:200px;
}
input[type="text"] {
width: 350px;
height:30px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>‌
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
var start_pos = new google.maps.LatLng(33.7167,73.0667);
function initialize() {
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(69.386,29.967),
new google.maps.LatLng(69.3451155,30.3753205)
);
var mapOptions = {
bounds:defaultBounds,
zoom:17,
center: start_pos
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var from = (document.getElementById('from'));
var to = (document.getElementById('to'));
var autocomplete = new google.maps.places.Autocomplete(from);
var autocomplete = new google.maps.places.Autocomplete(to);
autocomplete.bindTo('defaultBounds', map);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
codeAddress();
}
function calcRoute() {
var request = {
origin: document.getElementById('from').value,
destination: document.getElementById('to').value,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script>
$(document).ready(function(){
$('button').on('click',initialize);
});
</script>
</head>
<body>
<div id="map-canvas" style="float:left;width:60%; height:100%"></div>
<div id="from_to">
FROM: <input id="from" class="controls" type="text" placeholder="Enter a location">
<br/><br/><hr/>
TO: <input id="to" class="controls" type="text" placeholder="Enter a location">
<br/><hr/>
<button id="btn_refresh">Show route</button>
<p>Total Distance: <span id="total"></span></p>
</div>
NAVIGATION:
<div id="directionsPanel">
</div>
FROM NEW MARKER ADDRESS: <input type="text" id="addressmarker1" size="30">
<br/><br/><hr/>
TO NEW MARKER ADDRESS: <input type="text" id="addressmarker2" size="30">
</body>
</html>
Try this:
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
var directionsList = directionsDisplay.getDirections();
computeTotalDistance(directionsList);
document.getElementById("from").value = directionsList.routes[0].legs[0]["start_address"];
document.getElementById("to").value = directionsList.routes[0].legs[0]["end_address"];
});
You can also access other values:
//DISTANCE
document.getElementById("distance").value = directionsList.routes[0].legs[0]["distance"]["text"];
//DURATION
document.getElementById("duration").value = directionsList.routes[0].legs[0]["duration"]["text"];
//LATLNG POINT A
document.getElementById("fromLatLng").value = directionsList.routes[0].legs[0]["start_location"]["k"] + "," + directionsList.routes[0].legs[0]["start_location"]["B"] ;
//LATLNG POINT B
document.getElementById("toLatLng").value = directionsList.routes[0].legs[0]["end_location"]["k"] + "," + directionsList.routes[0].legs[0]["end_location"]["B"];
Please marked it solved if it helped

Uncaught InvalidValueError: unknown property origin

The code uses google maps api and draws the route between the selected points. But it is unable to calculate the distance between those two points on clicking the 'Calculate distances' button.
The error returned is:
Uncaught InvalidValueError: unknown property origin main.js:12 in the console log.
Code:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Trying Hard Now!</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="util.js"></script>
<style>
html, body{
height: 100%;
margin: 0px;
padding: 0px
}
#map_canvas {
height: 100%;
width: 100%;
}
#panel {
position: absolute;
height : 30%;
width: 20%
top: 30px;
left: 15%;
margin-left: -180px;
z-index: 5;
background-color: rgba(255,255,255,0);
padding: 5px;
}
#outputDiv {
font-size: 11px;
}
</style>
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var infowindow;
var map;
var origin = null;
var destination = null;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myLatlng = new google.maps.LatLng(19.1264,72.8790);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
downloadUrl("xmltaxi.php", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 6; i < 16; i=i+8) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
//var marker = createMarker(latlng);
if (i == 6)
origin = latlng;
else
destination = latlng;
}
});
//calcRoute();
}
/*function createMarker(latlng) {
var marker = new google.maps.Marker({position: latlng, map: map});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
//infowindow = new google.maps.InfoWindow({content: name});
infowindow.open(map, marker);
});
return marker;
}*/
//calcRoute();
function calcRoute() {
var selectedMode = document.getElementById('mode').value;
//var start = document.getElementById('start').value;
//var end = document.getElementById('end').value;
var request = {
origin:origin,
destination:destination,
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
//var origin = response.originAddresses;
//var destination = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
// deleteOverlays();
//for (var i = 0; i < origin.length; i++) {
var results = response.rows[0].elements;
//addMarker(origins[i], false);
//for (var j = 0; j < results.length; j++) {
//addMarker(destinations[j], true);
outputDiv.innerHTML += results[0].distance.text + ' in '
+ results[0].duration.text + '<br>';
//}
//}
}
}
//}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<b>Search: </b>
<select onchange="calcRoute();">
<option></option>
<option id="mode" value="DRIVING">Route</option>
</select>
<div id="inputs">
<p><button type="button" onclick="calculateDistances();">Calculate
distances</button></p>
</div>
<div id="outputDiv"></div>
</div>
<div id="map_canvas"></div>
</body>
</html>
It may be an extremely trivial mistake, so please help me out.
The DistanceMatrixRequest has no property origin, it should be origins. Likewise destination should be destinations. And it expects to receive these as arrays, not single LatLng objects.
service.getDistanceMatrix(
{
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
Should be
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);

Categories

Resources