I need to pass two addresses to the following code to show the direction between them based on chosen transportation mode. Once user selects two cities from the Dropdown box in page 1, I am going to send them to the code (page 2) to show their locations and direction between them.
I have copied this sample code from Google.I am now trying to combine it with my code but do not know how.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Travel modes in directions</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<style type="text/css">
html, body {
height: 50%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 200%;
width:25%;
}
#media print {
html, body {
height: auto;
}
#map-canvas {
height: 650px;
}
}
</style>
<script>
function GetLocation(add) {
var geocoder = new google.maps.Geocoder();
var address = add;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var output = latitude + "," + longitude;
return output;
} else {
alert("Request failed.")
}
});
};
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(-37.81411, 144.96327999999999);
var oceanBeach = new google.maps.LatLng(-37.814107, 144.96327999999994);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: haight
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var selectedMode = document.getElementById('mode').value;
var request = {
origin: haight,
destination: oceanBeach,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<b>Mode of Travel: </b>
<select id="mode" onchange="calcRoute();">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
<script>GetLocation("Los Angeles, USA");</script>
<script>GetLocation("Las Vegas, USA");</script>
</div>
<div id="map-canvas"></div>
</body>
</html>
You are essentially asking about SearchBox . You don't need it though. You can directly take a form and get the submitted values and Geocode it to be passed in the aforementioned script.
If you want to pass the two addresses to the 2nd page in the query string, you can do something like this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Travel modes in directions</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<style type="text/css">
html, body {
margin: 0;
padding: 0;
}
#map-canvas {
height: 500px;
width:600px;
}
</style>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var origin = "Los Angeles, USA";
var destination = "Las Vegas, USA";
var maptype = google.maps.MapTypeId.ROADMAP;
var travelMode = google.maps.TravelMode.DRIVING;
var arrivalTime = null;
var departureTime = null;
function initialize() {
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "origin") {origin = unescape(value);}
if (argname == "dest") {destination = unescape(value);}
if (argname == "type") {
if (value == "m") {maptype = google.maps.MapTypeId.ROADMAP;}
if (value == "k") {maptype = google.maps.MapTypeId.SATELLITE;}
if (value == "h") {maptype = google.maps.MapTypeId.HYBRID;}
if (value == "t") {maptype = google.maps.MapTypeId.TERRAIN;}
}
if (argname == "mode") {
if (value == "driving") {travelMode = google.maps.TravelMode.DRIVING; }
if (value == "walking") {travelMode = google.maps.TravelMode.WALKING; }
if (value == "transit") {travelMode = google.maps.TravelMode.TRANSIT; }
if (value == "bicycling") {travelMode = google.maps.TravelMode.BICYCLING; }
}
if (argname == "arrive") {
arrivalTime = new Date(value);
}
if (argname == "depart") {
departureTime = new Date(value);
}
}
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
calcRoute(origin, destination, travelMode, departureTime, arrivalTime);
}
function calcRoute(origin, destination, mode, departureTime, arrivalTime) {
var request = {
origin: origin,
destination: destination,
travelMode: mode,
};
if (travelMode == google.maps.TravelMode.TRANSIT)
request.transitOptions = {};
if (travelMode == google.maps.TravelMode.TRANSIT && !!departureTime)
request.transitOptions.departureTime = departureTime;
if (travelMode == google.maps.TravelMode.TRANSIT && !!arrivalTime)
request.transitOptions.departureTime = departureTime;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else alert("Directions Request failed: "+status);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="panel"></div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-162157-1";
urchinTracker();
</script>
</body>
</html>
working example
and working example with form input
Related
I need to find all the locations near by the lat long and radius provided.I think I can achieve this by using geofence but I don't know how to proceed.I have the following data.
set of lat long and to get the location for radius within 5km for all the lat long by each.
Any one help how to start this.
Inputs I have:
lat long
33.450909, -112.073196
33.466210, -112.064620
33.451640, -112.099130
33.437160, -112.048400
33.480860, -112.082130
33.489950, -112.074700
Tried so far:
<!DOCTYPE html >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Creating a Store Locator on Google Maps</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body style="margin:0px; padding:0px;" onload="initMap()">
<div>
<label for="raddressInput">Search location:</label>
<input type="text" id="addressInput" size="15"/>
<label for="radiusSelect">Radius:</label>
<select id="radiusSelect" label="Radius">
<option value="50" selected>50 kms</option>
<option value="30">30 kms</option>
<option value="20">20 kms</option>
<option value="10">10 kms</option>
</select>
<input type="button" id="searchButton" value="Search"/>
</div>
<div><select id="locationSelect" style="width: 10%; visibility: hidden"></select></div>
<div id="map" style="width: 100%; height: 90%"></div>
<script>
var map;
var markers = [];
var infoWindow;
var locationSelect;
function initMap() {
var sydney = {lat: 33.450909, lng: -112.073196};
map = new google.maps.Map(document.getElementById('map'), {
center: sydney,
zoom: 11,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
searchButton = document.getElementById("searchButton").onclick = searchLocations;
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'storelocator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var id = markerNodes[i].getAttribute("id");
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name;
locationSelect.appendChild(option);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAVD0ngfhOFs5rnww7UFyz9rN6UznOIZ1U&callback=initMap">
</script>
</body>
</html>
Using the above I can able to point single point,But what I want is to get the location around each lat long provided above radius is 5 km
If you are already using Google Maps, then I think you can try with computeDistanceBetween.
This is a short example of how to use it. You just need to eliminate those distances greater than the radius you set.
var home = ['Store', new google.maps.LatLng(29.520130, -98.415542)];
var pts = [
['Client A', new google.maps.LatLng(29.5197902, -98.3867079)],
['Client B', new google.maps.LatLng(29.5165967, -98.4235714)],
['Client C', new google.maps.LatLng(29.5198805, -98.3676648)]
];
var dist = google.maps.geometry.spherical.computeDistanceBetween;
pts.forEach(function(pt) {
console.log(home[0] + ' to ' + pt[0] + ': ' + (dist(home[1], pt[1])).toFixed(10));
});
I am trying to make a google map API that has moveable points but also includes a search option to search address. I have gotten the draggable points but get a Uncaught ReferenceError: SearchAddress is not defined at HTMLInputElement.onclick when I try and run this code. I cannot figure out how to get this to work. I have tried removing the SearchAddress function out of the other InitMap function but still Help would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Draggable directions</title>
<link rel="stylesheet" type="text/css" href="stylesheet1.css">
<script type="text/javascript">
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
var moveloc1 = {lat: 55, lng: -7.3};
var moveloc2 = {lat: 55, lng: -7.1};
function initMap()
{
console.log("error checker1");
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: {lat: 55, lng: -7.3} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer
({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function()
{
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute(moveloc1, moveloc2 , directionsService,
directionsDisplay);
console.log("error checker2");
function SearchAddress()
{
console.log("error checker3");
var locate1 = document.getElementById("pass1").value;
var locate2 = document.getElementById("pass2").value;
console.log(locate1);
console.log(locate2);
geocoder.geocode( { 'pass1': address}, function(results, status)
{
if (status == 'OK')
{
map.setCenter(results[0].geometry.location);
moveloc1 =
({
position: results[0].geometry.location
});
}
else
{
alert('Geocode was not successful for the following reason: ' +
status);
}
});
}
}
function displayRoute(origin, destination, service, display)
{
service.route
({
origin: origin,
destination: destination,
travelMode: 'DRIVING',
avoidTolls: true
},
function(response, status)
{
if (status === 'OK')
{
display.setDirections(response);
}
else
{
alert('Could not display directions due to: ' + status);
}
});
}
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;
document.getElementById('total').innerHTML = total + ' km';
}
</script>
</head>
<body>
<div id="map"></div>
<div id="right-panel">
<form>
Start<input class="textBox" id="pass1" type="text" maxlength="30" /> <br>
End<input class="textBox" id="pass2" type="text" maxlength="30" />
<input type = "button" id="button" name="button" value="search" onclick =
"SearchAddress()"/>
</form>
<p>Total Distance: <span id="total"></span></p>
</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyBtQt_1BqPPuSdIbXTuYW9I8yNUGIItPuk&callback=initMap">
</script>
</body>
</html>`
<script type="text/javascript">
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
var geocoder;
var moveloc1 = {lat: 55, lng: -7.3};
var moveloc2 = {lat: 55, lng: -7.1};
function SearchAddress()
{
console.log("error checker3");
var locate1 = document.getElementById("pass1").value;
var locate2 = document.getElementById("pass2").value;
console.log(locate1);
console.log(locate2);
// adress must be defined
geocoder.geocode( { 'pass1': adress}, function(results, status)
{
if (status == 'OK')
{
map.setCenter(results[0].geometry.location);
moveloc1 =
({
position: results[0].geometry.location
});
}
else
{
alert('Geocode was not successful for the following reason: ' +
status);
}
});
}
function initMap()
{
console.log("error checker1");
geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: {lat: 55, lng: -7.3} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer
({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function()
{
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute(moveloc1, moveloc2 , directionsService,
directionsDisplay);
console.log("error checker2");
}
function displayRoute(origin, destination, service, display)
{
service.route
({
origin: origin,
destination: destination,
travelMode: 'DRIVING',
avoidTolls: true
},
function(response, status)
{
if (status === 'OK')
{
display.setDirections(response);
}
else
{
alert('Could not display directions due to: ' + status);
}
});
}
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;
document.getElementById('total').innerHTML = total + ' km';
}
</script>
Problem:
Your problem is that you declared SearchAddress function inside of initMap function and you tried to access it from global scope (in the HTML element), which is impossible.
Explanation:
In fact a local functions and local variables can't be accessed from the global scope or from other functions. Note that in HTML elements events you can only access functions declared in the global windowscope.
You need to declare it in the global scope so you can access it from all functions and from HTML elements.
Note:
You need to fix that problem with all your functions declarations in your code.
I am trying to adapt this Google Maps distance calculator to my needs, but am not overly familiar with plain Javascript, and only Jquery.
I am trying to modify one of the destination variables so that it pulls it from a text box instead.
Usually the line reads :
var destinationA = 'pe219px';
But I am trying to change it to the following, usually I would do this with a keyup function to update the value as the person types in jquery, but im not sure what im doing in plain javascript. This is what I have come up with so far, but it doesn't appear to do a lot :
function setValue() {
destinationA=parseInt(document.getElementById('deliverypostcode').value);
}
This is the example I am trying to modify
https://developers.google.com/maps/documentation/javascript/examples/distance-matrix
This is the whole code :
<!DOCTYPE html>
<html>
<head>
<title>Distance Matrix service</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 50%;
}
#content-pane {
float:right;
width:48%;
padding-left: 2%;
}
#outputDiv {
font-size: 11px;
}
</style>
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = new google.maps.LatLng(53.003604, -0.532764);
var origin2 = 'pe219px';
function setValue() {
destinationA=parseInt(document.getElementById('deliverypostcode').value);
}
var destinationB = new google.maps.LatLng(53.003604, -0.532764);
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(53.003604, -0.532764),
zoom: 8
};
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, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
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 += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + '<br>';
}
}
}
}
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>
</head>
<body>
<div id="content-pane">
<div id="inputs">
<form name="form1" method="post" action="">
<label for="deliverypostcode">Your Postcode</label>
<input type="text" name="deliverypostcode" id="deliverypostcode">
</form>
<p><button type="button" onclick="calculateDistances();">Calculate
distances</button></p>
</div>
<div id="outputDiv"></div>
</div>
<div id="map-canvas"></div>
</body>
</html>
Your function setValue is never called.
What if you delete it and just place the following line at the begining of calculateDistances ?
var destinationA= document.getElementById('deliverypostcode').value;
This works for me. Also, you don't need to parseInt your text input. Geocoding converts strings to a lat/long coordinates.
I have a specific requirement where i have to display only railway stations in the map rather than the whole map. How can this be achieved.?. Please find the below code that i have tried.
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?libraries=drawing&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
// init map
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var drawingManager = new google.maps.drawing.DrawingManager();
drawingManager.setMap(map);
// init directions service
var dirService = new google.maps.DirectionsService();
var dirRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});
dirRenderer.setMap(map);
// highlight a street
// highlight a street
var request = {
origin: '',
destination: '',
travelMode: google.maps.TravelMode.TRANSIT
};
dirService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
dirRenderer.setDirections(response);
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var transitMode = steps[j].travel_mode;
if (transitMode == "TRANSIT") {
var vehicle = steps[j].transit.line.vehicle.type;
if (vehicle == "HEAVY_RAIL") {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
// polyline.getPath().push(nextSegment[k]);
}
}
}
}
}
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Any help will be much appreciated.. Thanks in advance..
I didn't understand what actually you want to do, but for this special kind of mapping you can rely on transit.js
It may be difficult,because:
Which is "Railway STATION"?, Platform?,Mark-on-rail?,Wickets?,Master'sRoom?,EntranceGate?
GoogleTransitService may show transfer by WALK via stair steps.
I have managed to create a simple map with a marked route between 2 destinations. Additionally, I need to pull the distance value and then do some basic math with it (multiply it by 2). It all works, but not on page load. More precise, map is displayed on page load as well as distance, but distance value doesn't get pulled and it doesn't get multiplied by 2. I have managed to make it work on mouse move, but it's not the perfect replacement.
Here is the code:
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false®ion=US"></script>
<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script src="http://www.pengoworks.com/workshop/jquery/calculation/jquery.calculation.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
var rendererOptions = {
draggable: false
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.directions);
});
calcRoute();
}
function calcRoute() {
var request = {
origin: 'Houston',
destination: 'Dallas',
travelMode: google.maps.DirectionsTravelMode.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.
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
function stripint() {
var val = $('[jsdisplay=distance]').text(); // get text content of <span jstcache="7">
// Replace using regex instead of strings, to catch more than the first match
val = val.replace(/\./g, "");
val = val.replace(/,/g, ".");
val = val.replace(/_/g, ",");
$('#dist').val(val);
}
function recalc() {
$("[id^='total_price_ht']").calc(
// the equation to use for the calculation
"di * 10", {
bind: "keyup",
di: $("[id^='dist']")
}, function(s) {
// return the number as a dollar amount
return "$" + s.toFixed(2);
});
}
$('#content').mousemove(function() {
stripint();
recalc();
});
stripint();
recalc();
});
</script>
</head>
<body>
<div id="content">
<p>Distance: <span id="total"></span>
</p>
<input type="text" value="0" name="dist" id="dist" />
<div id="total_price_ht_0" class="price">$0.00</div>
<div id="map-canvas" style="width:100%; height:500px"></div>
<div id="directionsPanel" style="width:100%; height:auto"></div>
</div>
</body>
first of all you don't need to use $(document).ready() because you already bind the initialize function to the window onLoad event google.maps.event.addDomListener(window, 'load', initialize);
what you want is wait until the directions and distance are calculated, you don't really need to read it from the directionsPanel, you can read whatever you need directly from the API response.
use the callback in calcRoute like this:
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
dist = response.routes[0].legs[0].distance.text;
stripint(dist);
recalc();
}
});
you also need to add the dist argument to you strprint:
function stripint(val) {
// Replace using regex instead of strings, to catch more than the first match
val = val.replace(/\./g, "");
val = val.replace(/,/g, ".");
val = val.replace(/_/g, ",");
$('#dist').val(val);
}
so your new code doesn't use document.ready and calculates the price immediately when the API responds.
the new <script> tag:
var rendererOptions = {
draggable: false
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
computeTotalDistance(directionsDisplay.directions);
});
calcRoute();
}
function calcRoute() {
var request = {
origin: 'Houston',
destination: 'Dallas',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
dist = response.routes[0].legs[0].distance.text;
stripint(dist);
recalc();
}
});
}
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.
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
function stripint(val) {
// Replace using regex instead of strings, to catch more than the first match
val = val.replace(/\./g, "");
val = val.replace(/,/g, ".");
val = val.replace(/_/g, ",");
$('#dist').val(val);
}
function recalc() {
$("[id^='total_price_ht']").calc(
// the equation to use for the calculation
"di * 10", {
bind: "keyup",
di: $("[id^='dist']")
}, function (s) {
// return the number as a dollar amount
return "$" + s.toFixed(2);
});
}
here is no need to have two tags; you can put everything inside one. Some of your functions use jQuery selectors, try to put all of them inside the $(document).ready(), this will guarantee that all the selected elements are available by the time they are called:
$(document).ready(function(){
//Insert your functions with selectors here
});
Here is the rearranged code with everything inside document.ready: http://jsbin.com/iqejiy/1/edit
Hope it helps.
i think you are missing document.ready() here.