How to get the distance of a route using Bing maps API? - javascript

The "function" that I need is in this link, but there is not a code example, just "RouteSummary Object" and the bellow there is the "distance", which is what I need.
I got the code bellow in this link
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
</head>
<body>
<div id='printoutPanel'></div>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
<script type='text/javascript'>
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
/* No need to set credentials if already passed in URL */
center: new Microsoft.Maps.Location(47.606209, -122.332071),
zoom: 12
});
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function () {
var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
// Set Route Mode to driving
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
var waypoint1 = new Microsoft.Maps.Directions.Waypoint({ address: 'Redmond', location: new Microsoft.Maps.Location(47.67683029174805, -122.1099624633789) });
var waypoint2 = new Microsoft.Maps.Directions.Waypoint({ address: 'Seattle', location: new Microsoft.Maps.Location(47.59977722167969, -122.33458709716797) });
directionsManager.addWaypoint(waypoint1);
directionsManager.addWaypoint(waypoint2);
// Set the element in which the itinerary will be rendered
directionsManager.calculateDirections();
});
}
</script>
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?key=AnOeSZ6a7LgcnBLVjmZ4xfQWIWZjzKv7bDwgyRk-W4NlkGnZGQdk5atUjsunU5yH&callback=loadMapScenario' async defer></script>
</body>
</html>
I tried like that ways:
routeSummary.distance();
and too:
directionsManager.routeSummary.distance();
I don't know almost anything about JavaScript and don't know how to read documentation.
after all, how do I use an Object like described in the documentation?
I just want to know what mean by "object" in this case, is the class-related object of OOP or not?

You need to add an event to the directions manager since the route calculation is done asynchronously. Here is an example:
Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', directionsUpdated);
function directionsUpdated(e) {
//Get the current route index.
var routeIdx = directionsManager.getRequestOptions().routeIndex;
//Get the distance of the route.
var distance = .routeSummary[routeIdx].distance;
}

Related

Bahrain's transit route in bings map

I want to display the transit route from point A to B on the Bahrain map. I'm not sure what the issue is because when I entered the route mode as "driving/walk" a path is displayed but when its "transit" nothing shows up.
Note: I have removed my map's API key from the credentials in the code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script type='text/javascript'
src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap'
async defer></script>
<script type='text/javascript'>
var map;
var directionsManager;
function GetMap()
{
var map = new Microsoft.Maps.Map('#myMap', {
credentials: '',
});
//Load the directions module.
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function () {
//Create an instance of the directions manager.
var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
//Calculate a date time that is 1 hour from now.
var departureTime = new Date();
departureTime.setMinutes(departureTime.getHours() + 1);
//Set Route Mode to transit.
directionsManager.setRequestOptions({
routeMode: Microsoft.Maps.Directions.RouteMode.transit,
time: departureTime,
timeType: Microsoft.Maps.Directions.TimeTypes.departure
});
//Add waypoints.
var w1 = new Microsoft.Maps.Location(26.230570, 50.577430);
var waypoint1 = new Microsoft.Maps.Directions.Waypoint({ location: w1 });
directionsManager.addWaypoint(waypoint1);
var w2 = new Microsoft.Maps.Location(26.227840, 50.494110);
var waypoint2 = new Microsoft.Maps.Directions.Waypoint({ location: w2 });
directionsManager.addWaypoint(waypoint2);
//Set the element in which the itinerary will be rendered.
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
//Calculate directions.
directionsManager.calculateDirections();
});
}
</script>
</head>
<body>
<div id="myMap" style="position:relative;width:800px;height:600px;"></div>
<div id='directionsItinerary'></div>
</body>
</html>
Transit routing is not supported in all areas. For a list of supported transit markets, see https://msdn.microsoft.com/en-us/library/hh441739.aspx

Linking Google Script Variable to the Javascript in HTML

So I feel I'm almost there to the solution but I'm really in need of help here. What I'm trying to do is to create an array using .getValues() to get a range that contains four columns (Name, Address, Latitude, and Longitude). After that I want to return the variable back into a global variable and then call that variable from the HTML side. I tried linking the google script with the HTML and then calling the variable there but having quite a bit of trouble with that. Thank you guys for all of your help!
Below is the google script:
var id = 'Spreadsheet Key';
function doGet(e) {
var html = HtmlService.createTemplateFromFile('Sample');
return html.evaluate().setTitle('Directory Map');
}
function entries() {
var blop =
SpreadsheetApp.openById(id).getSheetByName('Sheet1').getRange('A1:D').getValues();
return blop;
}
This is the HTML in Google Script.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.8283, lng: -98.5795},
zoom: 5,
mapTypeId: 'roadmap',
gestureHandling: 'greedy'
});
var locations = [blop];
for (var i = 0; i < locations.length; i++) {
var sites = locations[i];
var myLatLng = new google.maps.LatLng(sites[2],sites[3]);
var sites = new google.maps.Marker({
position: myLatLng,
map: map,
title: sites[0],
});
};
}
</script>
<script> google.script.run.entries(); </script>
<script src="https://maps.googleapis.com/maps/api/js?key=MyAPIKey&libraries=places&callback=initAutocomplete"async defer></script>
<script src="https://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="SampleCode.gs"></script>
</body>
</html>
The starting point is:
<script> google.script.run.entries(); </script>
The above code runs when the page is loaded in the browser. You need a "success handler", and then the success handler can store the data somewhere. You could put the data into a window variable, or local browser storage.
<script>
window.storeSheetValues = function(theReturnedData) {
console.log('theReturnedData: ' + theReturnedData)
console.log('typeof theReturnedData: ' + typeof theReturnedData)
window.mySheetData = theReturnedData;//Put the data into a window variable
}
google.script.run
.withSuccessHandler(storeSheetValues)
.entries();
</script>
Check the data type of the return value coming back from the server. If it's a string, you may want to turn it back into an array.

Values not passing from html form to Javascript, variables logging undefined, why?

I'm trying to make a small site for class that will changes maps based on drop down selection. The first map pops up fine because I have the lat and long values hard coded, but when you use the drop down box, the values come back undefined. I dont think it's being passed correctly and I can't figure out why.
<!DOCTYPE HTML>
<head>
<meta charset='utf-8'>
<link href ='style.css' rel='stylesheet' />
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[hidden]"></script>
<title>Geolocation</title>
</head>
<body>
<div id="map"></div>
<div id="formArea">
<form>
<h1>Famous Cities</h1>
<fieldset>
<label>Cities</label>
<select id="selectedCity" name="selectedCity">
<option value='None'>Please select a city from the dropdown</option>
<option value='ITA'>Rome, Italy</option>
<option value='FRA'>Paris, France</option>
<option value='USA'>New York, USA</option>
</select>
</fieldset>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src='script.js'></script>
</body>
</html>
and the JS file is below
var map;
function initMap() {
var mapDisplay = document.getElementById('map');
var mapOptions = {
center: new google.maps.LatLng(40.7484,-73.9857),
zoom: 8
};
map = new google.maps.Map(mapDisplay, mapOptions);
console.log('now exiting initMap');
}
var coordsLat = {
'ITA':41.9028,
'FRA':48.8566,
'USA':40.7128,
};
var coordsLng = {
'ITA': 12.4964,
'FRA': 2.3522,
'USA': -74.0060
};
function changeSelection(loc) {
var lac = coordsLat[loc];
var lgc = coordsLng[loc];
map.setCenter(new google.maps.LatLng(lac, lgc));
console.log('selection changed')
console.log('new coordinates are now: ' + lac +" : " + lgc);
}
$(document).ready(function(){
$(window).on('load', function(){
initMap();
$("#selectedCity").change(changeSelection);
});
});
It's so because you pass an Event object to the changeSelection method. You need to pass a value instead:
$("#selectedCity").change(function() {
changeSelection($(this).val());
});
This would work because jQuery sets this within the handler's callback to a DOM element. Per jQuery doc:
Whenever you call jQuery's .each() method or one of its event methods
on a jQuery collection, the context of the callback function — this —
is set to a DOM element.
you are calling
$("#selectedCity").change(changeSelection);
while your function changeSelection needs a parameter
function changeSelection(loc) { ... }
you probably want to get the value of the select, therefore I would recommend:
$("#selectedCity").change(function({changeSelection($("#selectedCity").options[$("#selectedCity").selectedIndex].value);});

Passing Variables by Reference in JavaScript

I am trying to display and center a map for the users current location. Everything works fine if I manually enter a hard coded latitude and longitude, but these needs to be dynamic as one user often changes location.
I suspect I am making a basic mistake, but my logic seems like it is correct to me. Please check my work and let me know what I am doing wrong? The line that is remarked out with Latitude and Longitude is the line I want to use instead of the previous line with the hard coded values.
<!DOCTYPE html>
<html>
<head>
<title>W123</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
</head>
<body>
<div id='printoutPanel'></div>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
<script type='text/javascript'>
function showlocation() {
navigator.geolocation.getCurrentPosition(getLocation);
}
function getLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
}
function loadMapScenario() {
var mapOptions = {
credentials: 'My API key code goes here',
center: new Microsoft.Maps.Location(39.1887643719098, -92.8261546188403),
//center: new Microsoft.Maps.Location(latitude, longitude),
mapTypeId: Microsoft.Maps.MapTypeId.road,
zoom: 8
};
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), mapOptions);
var urlTemplate = 'http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-{timestamp}/{zoom}/{x}/{y}.png';
var timestamps = ['900913-m50m', '900913-m45m', '900913-m40m', '900913-m35m', '900913-m30m', '900913-m25m', '900913-m20m', '900913-m15m', '900913-m10m', '900913-m05m', '900913'];
var tileSources = [];
for (var i = 0; i < timestamps.length; i++) {
var tileSource = new Microsoft.Maps.TileSource({
uriConstructor: urlTemplate.replace('{timestamp}', timestamps[i])
});
tileSources.push(tileSource);
}
var animatedLayer = new Microsoft.Maps.AnimatedTileLayer({ mercator: tileSources, frameRate: 500 });
map.layers.insert(animatedLayer);
}
</script>
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=experimental&callback=loadMapScenario' async defer></script>
</body>
</html>
You want to pass in the latitude and longitude into your loadMapScenario function as seen below
function loadMapScenario(latitude,longitude) {
....your code here....
}
Change your callback in the bing map include to a new function like "mapUserLocation" then have mapUserLocation perform the following tasks
function mapUserLocation() {
// code here to get the latitude and longitude from users position
loadMapScenario(latitude,longitude);
}

Windows Store App - WinJS: 0x800a1391 - JavaScript runtime error: 'Windows' is undefined

I'm trying to load a Google map into Windows Store Application. However, having a problem with a native Windows RT function: Windows.UI.Popups.MessageDialog. I'm guessing that the Windows namespace is out of scope, but I can't figure out now to get this function into a scope that will make the Windows namespace accessible. Any help is appreciated.
EDIT: the more I think about this, the more I think it has something to do with the fact that I am loading map.html as the source for an iFrame. So the context of map.html is an iFrame, not a Windows Store App page. I guess the Windows namespace is not available from within an iFrame?
From home.html:
<iframe id="getLocationFrame" src="ms-appx-web:///pages/map/map.html" style="width:600px; height:600px;"></iframe>
Exception:
SCRIPT5009: Unhandled exception at line 50, column 17 in ms-appx-web://76ad865e-25cf-485c-bc77-e18186bfd7ee/pages/map/map.js
0x800a1391 - JavaScript runtime error: 'Windows' is undefined
File: map.js, Line: 50, Column: 17
map.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script type="text/javascript" src="//Microsoft.WinJS.1.0/js/ui.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js? sensor=false"></script>
<script type="text/javascript" src="map.js"></script>
<link href="/pages/map/css/map.css" rel="stylesheet" />
<link href="//Microsoft.WinJS.1.0/css/ui-light.css" rel="stylesheet" />
</head>
<body>
<p>Click to get your location.</p>
<button id="getLocation">Get Location</button><br/>
<div id="mapcontainer"></div><br />
<small>
<a id="anchorLargerMap" href="" style="color:#0000FF;text-align:left" target="_blank">View Larger Map</a>
</small>
</body>
</html>
map.js:
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/map/map.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
//Button "getLocation" event handler
function getLocationClickHandler(eventInfo) {
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapcontainer = document.getElementById("mapcontainer");
var map = new google.maps.Map(mapcontainer, myOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess, locationFail);
}
}
var namespacePublicMembers = {
locationSucessFunction: locationSuccess,
locationFailFunction: locationFail,
getLocationClickEventHandler: getLocationClickHandler
};
WinJS.Namespace.define("mapPage", namespacePublicMembers);
var getLocationButton = document.getElementById("getLocation");
getLocationButton.addEventListener("click", getLocationClickHandler, false);
function locationSuccess(position) {
var initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
position: initialLocation,
map: map,
title: "You are here."
});
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var url = "http://maps.google.com/maps?q=" + latitude + "," + longitude + "&zoom=13&markers=" + latitude + "," + longitude;
$("#anchorLargerMap").attr('href', url);
}
function locationFail() {
var md = new Windows.UI.Popups.MessageDialog("Could not find you!", "").showAsync; -- ********* THIS LINE THROWS EXCEPTION *********
}
}
});
})();
Code that is executed in the web compartment - your URL says that's where this code is - cannot access WinRT components. You'll need to use postMessage etc to communicate between the two security contexts.
from Map.js:
function locationFail() {
//Can't do this due the the iFrame container
//var md = new Windows.UI.Popups.MessageDialog("Could not find you!", "").showAsync;
window.parent.postMessage("Could not find you!", "*");
}
from Home.js:
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/home/home.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
window.addEventListener("message", messageReceived, false);
function messageReceived(e) {
if (e.origin === "ms-appx-web://76ad865e-25cf-485c-bc77-e18186bfd7ee") {
var md = new Windows.UI.Popups.MessageDialog(e.data, "");
md.showAsync();
}
};
}
});
})();
I got the solution from this blog: http://css.dzone.com/articles/use-winjs-post-message-iframe

Categories