Cesium live update of a point? - javascript

I am currently working on a live tracking application for Cesium, but am having some issues when I display the point in the browser.
So far my Cesium viewer receives the data from the server (in JSON format) and displays the point properly on the map, but the only way to have it update the location on the map is to refresh the page. Note that the location.json file it is reading the location from is being updated with a new location every second or so from the server.
Now I figured it would do this, as the client side code has no "update" function to dynamically change the point location on the map.
So what is the easiest way to have Cesium constantly update the point on the map, without the user constantly refreshing the page? Based on my research I have found some examples that involve streaming of CZML files or making my JSON into a data source, but these seem a bit complex for what seems to be a simple task. Is there not a simple "update" function that will change the point dynamically?
Here is my client side code:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Use correct character set. -->
<meta charset="utf-8">
<!-- Tell IE to use the latest, best version (or Chrome Frame if pre-IE11). -->
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<!-- Make the application on mobile take up the full browser screen and disable user scaling. -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<title>Hello World!</title>
<script src="../Build/Cesium/Cesium.js"></script>
<style>
#import url(../Build/Cesium/Widgets/widgets.css);
html, body, #cesiumContainer {
width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
}
</style>
</head>
<body>
<div id="cesiumContainer"></div>
<script>
var viewer = new Cesium.Viewer('cesiumContainer');
Cesium.loadJson('/location.json').then(function(data) {
console.log(data);
viewer.entities.add({
name : data.name,
position : Cesium.Cartesian3.fromDegrees(data.lon, data.lat),
point : {
pixelSize : 5,
color : Cesium.Color.RED,
outlineColor : Cesium.Color.WHITE,
outlineWidth : 2
},
label : {
text : data.name,
font : '14pt monospace',
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth : 2,
verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
pixelOffset : new Cesium.Cartesian2(0, -9)
}
});
viewer.zoomTo(viewer.entities);
});
</script>
</body>
</html>
If you need any more information from me, I will be happy to provide it.
Thanks!

You will need to keep a reference to each of this points and then simply update that elements position according to some unique id. If a name is unique then you can use that, otherwise you need to implement some way to identify each point after update.
You can check if the point is a new one or existing one in a loadJSON callback function by calling var currentPoint = viewer.entities.getById(data.id). Then you can choose which one of these function will you call. First one for new points (when currentpoint == undefined):
function addNewPoint(
var point = new Cesium.Entity(
{
id : data.id,
name : data.name,
position : Cesium.Cartesian3.fromDegrees(data.lon, data.lat),
point : {
pixelSize : 5,
color : Cesium.Color.RED,
outlineColor : Cesium.Color.WHITE,
outlineWidth : 2
},
label : {
text : data.name,
font : '14pt monospace',
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth : 2,
verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
pixelOffset : new Cesium.Cartesian2(0, -9)
}
}
);
viewer.entities.add(point);
);
Otherwise you call updatePoint function that will just update position
function updatePosition(currentPoint, data)
{
var newPos = new Cesium.Cartesian3.fromDegrees(data.lon, data.lat);
currentPoint.position = newPos;
}

Related

How to incorporate Javascript embbeded atlas based animation in HTML5 properly

So I used Adobe Animate to publish a vector based animation. It uses a basic .png atlas to play a 18 fps loop. It is 8 bit. Basically, I want to reference the atlas via a site source location like https://static.wixstatic.com/media/user/RECOVER_Banner%20Flash_atlas_.png. I have limited experience with Javascript so I don't know how to modify this code to reference the atlas from a site location properly.
<html>
<head>
<meta charset="UTF-8">
<meta name="authoring-tool" content="Adobe_Animate_CC">
<title>RECOVER_Banner Flash</title>
<!-- write your code here -->
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script>
(function (cjs, an) {
var p; // shortcut to reference prototypes
var lib={};var ss={};var img={};
lib.ssMetadata = [
{name:"RECOVER_Banner Flash_atlas_", frames: [[802,6020,800,600],[1604,1204,800,600],[802,6622,800,600],[1604,4816,800,600],[802,5418,800,600],[1604,5418,800,600],[0,2408,800,600],[0,7224,800,600],[802,7224,800,600],[1604,0,800,600],[802,4214,800,600],[1604,1806,800,600],[802,1806,800,600],[1604,3010,800,600],[802,1204,800,600],[1604,3612,800,600],[0,602,800,600],[0,0,800,600],[0,3010,800,600],[0,1204,800,600],[0,5418,800,600],[0,1806,800,600],[1604,602,800,600],[0,3612,800,600],[1604,2408,800,600],[1604,4214,800,600],[802,2408,800,600],[0,4214,800,600],[0,6020,800,600],[0,4816,800,600],[802,0,800,600],[802,4816,800,600],[0,6622,800,600],[802,602,800,600],[802,3010,800,600],[802,3612,800,600],[2406,7224,800,600],[3208,1204,800,600],[2406,2408,800,600],[3208,0,800,600],[2406,5418,800,600],[3208,5418,800,600],[3208,602,800,600],[2406,6020,800,600],[1604,6622,800,600],[4010,3010,800,600],[2406,3010,800,600],[2406,3612,800,600],[3208,1806,800,600],[4010,4214,800,600],[3208,4816,800,600],[3208,6020,800,600],[3208,2408,800,600],[3208,3010,800,600],[2406,4214,800,600],[4010,3612,800,600],[1604,7224,800,600],[2406,4816,800,600],[4010,0,800,600],[3208,3612,800,600],[2406,0,800,600],[2406,6622,800,600],[3208,4214,800,600],[2406,602,800,600],[3208,6622,800,600],[3208,7224,800,600],[4010,602,800,600],[2406,1204,800,600],[2406,1806,800,600],[4010,1204,800,600],[4010,1806,800,600],[4010,2408,800,600],[1604,6020,800,600]]}
];
Here is what I think is the atlas source that I tried changing to the https location
lib.properties = {
id: '32FF965B604FBF408600E883266E961F',
width: 800,
height: 600,
fps: 24,
color: "#FFFFFF",
opacity: 1.00,
manifest: [
{src:"https://static.wixstatic.com/media/user/RECOVER_Banner%20Flash_atlas_.png", id:"RECOVER_Banner Flash_atlas_"}
],
preloads: []

Animate an icon by using serious of Lat/lon Array - Mapbox js

I am modifying bellow script to see how can i move an Icon by following Array of Lat/lon , but it always say error such , but I am providing as an Array
Can any one please help me to understand what i am doing wrong ?
I am revering this example
https://www.mapbox.com/mapbox-gl-js/example/animate-marker/
Error :
lng_lat.js:121 Uncaught Error: `LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]
at Function.yu.convert (lng_lat.js:121)
at o.setLngLat (marker.js:251)
at animateMarker (animate.html:33)
Modified Code : -
<html>
<head>
<meta charset='utf-8' />
<title>Animate a marker</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = '';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [90.35388165034988, 23.725173272533567],
zoom: 10
});
var marker = new mapboxgl.Marker();
function animateMarker() {
var radius = 20;
// Update the data to a new position based on the animation timestamp. The
// divisor in the expression `timestamp / 1000` controls the animation speed.
marker.setLngLat([
 [90.35388165034988, 23.725173272533567],
 [90.37379437008741, 23.732873570085644] ,
[90.38563900508132, 23.72297310398119],
[90.35388165034988, 23.725173272533567],
[90.35388165034988, 23.725173272533567]
]);
// Ensure it's added to the map. This is safe to call if it's already added.
marker.addTo(map);
// Request the next frame of the animation.
requestAnimationFrame(animateMarker);
}
// Start the animation.
requestAnimationFrame(animateMarker);
</script>
</body>
</html>
You can only pass a single coordinate to setLngLat. You cannot pass an array. Here's a crude example where inside the animation function, we use time to pick a position from the array of points and pass that one position to the marker.
var controlPoints = [
[90.35388165034988, 23.725173272533567],
[90.37379437008741, 23.732873570085644] ,
[90.38563900508132, 23.72297310398119],
[90.35388165034988, 23.725173272533567],
[90.35388165034988, 23.725173272533567]
];
function animateMarker(timestamp) {
// stay at each point for 1 second, then move to the next
// (lower 1000 to 500 to move 2x as fast)
var position = Math.floor(timestamp / 1000) % controlPoints.length;
marker.setLngLat(controlPoints[position])
// Ensure it's added to the map. This is safe to call if it's already added.
marker.addTo(map);
// Request the next frame of the animation.
requestAnimationFrame(animateMarker);
}
This animation will be crude. Ideally, you'd take those control points and create a polyline or linear ring, then your animation function would interpolate along the polyline at a set speed (like 30 km/s). You would end up with a very nice animation that followed the path of the control points.

Dojo/Dijit TooltipDialog.open: How to override offsetHeight and offsetTop values

Currently trying to implement/solve an issue with an ESRI ArcGIS map environment where I have a multi-layered map with custom graphics being rendered in each layer. Some of the graphics are simple shapes such as lines and circles, but a majority of the graphics are icons (.png) files that are being drawn on the layers. (All of this is being done in JavaScript.)
I have been able to get all of the layers generated correctly - the data IS NOT being stored in ArcGIS maps but a custom designed Contact & Location database (SQL) and other forms within the web application maintain this C&L data.
The graphic icons that are rendered on the map need to have a mouse-over tooltip popup appear with information that has been stored with the icon when it is created where the .substitute() command will update the template. The information displayed is HTML formatted in a <div>.
Problem:
When the mouse is moved over an icon, the tooltipDialog appears but 1) it always appears in the lower right corner of the screen - despite "orient:" and specific "x:" and "y:" coordinates being specified. Additionally when the tooltipDialog.open() command is executed, the dialog's offsetHeight is set to 624 and the offsetTop is set to 502. (The offsetWidth is actually set to the correct value.) How do I override either/both the offsetHeight/offsetTop?
I have tried specifying additional parameters to the tooltipDialog.open() command but nothing tried so far has altered the outcome. Even when I change the template content to be as simple as "Hi There!" does not change the outcome.
Note: If I click on an icon the IconWindow dialog will popup with the proper content and formatting being displayed. So it leads me to believe that the issue is within CSS or some other aspect of dojo/dijit as the tooltipDialog.open() command is actually where the offset changes are being made - the values are retained (offsetTop=0 offsetHeight=0) prior to the open() call.
Ideas/Recommendations?
You could try to use the dijit/popup module to open the TooltipDialog, which would allow you to pass in the DOM node around which the tooltip should be opened:
popup.open({
popup: myTooltipDialog,
around: dom.byId('thenode')
});
There a full example of this here (next to "A TooltipDialog may be popped up from any node.")
Well, It seems like you want to show info popup with some offset value whenever you hover on any feature on the map.
Solution-
Well to do so i don't think you need to deal with TooltipDialog because whenever you are loading feature or feature layer on the map you can attach info popup to it. It will take care of entire loading and displaying info popup Dialog along with its positioning.
To pass offset value-
If want to pass some offset value to popup dialog you can use below mentioned properties:-
For more Properties of popup dialog refer this link- https://developers.arcgis.com/javascript/3/jsapi/popup.html
Hovering Dialog sample-
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Feature Layer - display results as an InfoWindow onHover</title>
<link rel="stylesheet" href="https://js.arcgis.com/3.18/dijit/themes/tundra/tundra.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/css/esri.css">
<style>
html, body, #mapDiv {
padding:0;
margin:0;
height:100%;
}
#mapDiv {
position: relative;
}
#info {
background: #fff;
box-shadow: 0 0 5px #888;
left: 1em;
padding: 0.5em;
position: absolute;
top: 1em;
z-index: 40;
}
</style>
<script src="https://js.arcgis.com/3.18/"></script>
<script>
var map, dialog;
require([
"esri/map", "esri/layers/FeatureLayer",
"esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleLineSymbol",
"esri/renderers/SimpleRenderer", "esri/graphic", "esri/lang",
"esri/Color", "dojo/number", "dojo/dom-style",
"dijit/TooltipDialog", "dijit/popup", "dojo/domReady!"
], function(
Map, FeatureLayer,
SimpleFillSymbol, SimpleLineSymbol,
SimpleRenderer, Graphic, esriLang,
Color, number, domStyle,
TooltipDialog, dijitPopup
) {
map = new Map("mapDiv", {
basemap: "streets",
center: [-80.94, 33.646],
zoom: 8,
slider: false
});
var southCarolinaCounties = new FeatureLayer("https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/3", {
mode: FeatureLayer.MODE_SNAPSHOT,
outFields: ["NAME", "POP2000", "POP2007", "POP00_SQMI", "POP07_SQMI"]
});
southCarolinaCounties.setDefinitionExpression("STATE_NAME = 'South Carolina'");
var symbol = new SimpleFillSymbol(
SimpleFillSymbol.STYLE_SOLID,
new SimpleLineSymbol(
SimpleLineSymbol.STYLE_SOLID,
new Color([255,255,255,0.35]),
1
),
new Color([125,125,125,0.35])
);
southCarolinaCounties.setRenderer(new SimpleRenderer(symbol));
map.addLayer(southCarolinaCounties);
map.infoWindow.resize(245,125);
dialog = new TooltipDialog({
id: "tooltipDialog",
style: "position: absolute; width: 250px; font: normal normal normal 10pt Helvetica;z-index:100"
});
dialog.startup();
var highlightSymbol = new SimpleFillSymbol(
SimpleFillSymbol.STYLE_SOLID,
new SimpleLineSymbol(
SimpleLineSymbol.STYLE_SOLID,
new Color([255,0,0]), 3
),
new Color([125,125,125,0.35])
);
//close the dialog when the mouse leaves the highlight graphic
map.on("load", function(){
map.graphics.enableMouseEvents();
map.graphics.on("mouse-out", closeDialog);
});
//listen for when the onMouseOver event fires on the countiesGraphicsLayer
//when fired, create a new graphic with the geometry from the event.graphic and add it to the maps graphics layer
southCarolinaCounties.on("mouse-over", function(evt){
var t = "<b>${NAME}</b><hr><b>2000 Population: </b>${POP2000:NumberFormat}<br>"
+ "<b>2000 Population per Sq. Mi.: </b>${POP00_SQMI:NumberFormat}<br>"
+ "<b>2007 Population: </b>${POP2007:NumberFormat}<br>"
+ "<b>2007 Population per Sq. Mi.: </b>${POP07_SQMI:NumberFormat}";
var content = esriLang.substitute(evt.graphic.attributes,t);
var highlightGraphic = new Graphic(evt.graphic.geometry,highlightSymbol);
map.graphics.add(highlightGraphic);
dialog.setContent(content);
domStyle.set(dialog.domNode, "opacity", 0.85);
dijitPopup.open({
popup: dialog,
x: evt.pageX,
y: evt.pageY
});
});
function closeDialog() {
map.graphics.clear();
dijitPopup.close(dialog);
}
});
</script>
</head>
<body class="tundra">
<div id="mapDiv">
<div id="info">
Hover over a county in South Carolina to get more information.
</div>
</div>
</body>
</html>
Hoping this will help you :)
However its always recommended to add your code here if you are looking for exact Fix.
Found the answer to my situation. There is what appears to be an unstated requirement that either one of the supplied CSS dijit/themes be utilized OR the user must create their own theme which has some CSS that configures the display location.
The offsetTop issue was resolved by using eliminating any style references to top:.

Here.com (Nokia Api for Maps) : How to manage circles with changing colors on click?

I'm using the Nokia API for my web app (Javascript), and I draw circles in my map with different radium. The thing is when I zoom in, the circle has the same size, which means that when I zoom in, there's a level where I can't see anything else since it covers the whole map. Hence, I want the circle to keep the same size even if I zoom in.
For that, I tried SVG Markers, which solve this problem, but the thing is I had to program when I click on one of them, the color has to change (it's all a mess, and it reduces the performance of the app).
If anyone can help me, that would be awesome !
There are three key points which need to be answered to find a solution your question.
To add functionality when a marker is clicked, you need to add a listener to the click event i.e. marker.addListener("click", function (evt) { ...etc
To switch the color of an SVG marker you need two separate icons for that marker. The icon property is immutable, and hence it should only be updated using the set() method i.e. marker.set("icon", markerIcon);
To force a refresh of the screen after the new icon has been set you need to update the map display - map.update(-1, 0);
Combining these points togther there is a working example appended below. You need to substitute in your own app id and token to get it to work of course.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9" />
<title>Highlighing a marker: Istanbul (Not Constantinople)</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script language="javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<p> Click on the marker to change it.</p>
<div id="gmapcanvas" style="width:600px; height:600px;" > </div><br/><br/>
<script type="text/javascript">
// <![CDATA[
/////////////////////////////////////////////////////////////////////////////////////
// Don't forget to set your API credentials
//
// Replace with your appId and token which you can obtain when you
// register on http://api.developer.nokia.com/
//
nokia.Settings.set( "appId", "YOUR APP ID GOES HERE");
nokia.Settings.set( "authenticationToken", "YOUR AUTHENTICATION TOKEN GOES HERE");
/////////////////////////////////////////////////////////////////////////////////////
map = new nokia.maps.map.Display(document.getElementById('gmapcanvas'), {
'components': [
// Behavior collection
new nokia.maps.map.component.Behavior(),
new nokia.maps.map.component.ZoomBar()
],
'zoomLevel': 5, // Zoom level for the map
'center': [41.0125,28.975833] // Center coordinates
});
// Remove zoom.MouseWheel behavior for better page scrolling experience
map.removeComponent(map.getComponentById("zoom.MouseWheel"));
var iconSVG =
'<svg width="33" height="33" xmlns="http://www.w3.org/2000/svg">' +
'<circle stroke="__ACCENTCOLOR__" fill="__MAINCOLOR__" cx="16" cy="16" r="16" />' +
'<text x="16" y="20" font-size="10pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="__ACCENTCOLOR__" textContent="__TEXTCONTENT__">__TEXT__</text>' +
'</svg>',
svgParser = new nokia.maps.gfx.SvgParser(),
// Helper function that allows us to easily set the text and color of our SVG marker.
createIcon = function (text, mainColor, accentColor) {
var svg = iconSVG
.replace(/__TEXTCONTENT__/g, text)
.replace(/__TEXT__/g, text)
.replace(/__ACCENTCOLOR__/g, accentColor)
.replace(/__MAINCOLOR__/g, mainColor);
return new nokia.maps.gfx.GraphicsImage(svgParser.parseSvg(svg));
};
/* On mouse over we want to change the marker's color and text
* hence we create two svg icons which we flip on mouse over.
*/
var markerText = "1";
var colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#00FFFF", "#FF00FF" , "#000000"];
var markerIcon= createIcon("1", "#F00", "#FFF");
map.addListener("click", function (evt) {
var target = evt.target;
if (target instanceof nokia.maps.map.Marker && (target.clickCount === undefined) == false){
target.clickCount++;
var icon = createIcon(target.clickCount, colors[target.clickCount%7], "#FFF");
target.set("icon", icon);
map.update(-1, 0);
}
if (evt.target instanceof nokia.maps.map.Spatial) {
evt.stopImmediatePropagation();
}
});
var istanbul = new nokia.maps.map.Marker(
// Geo coordinate of Istanbul
[41.0125,28.975833],
{
icon: markerIcon,
clickCount : 1
}
);
/// Let's add another marker for comparison:
var bucharest = new nokia.maps.map.Marker(
// Geo coordinate of Bucharest
[44.4325, 26.103889],
{
icon: markerIcon,
clickCount: 1
}
);
// We add the marker to the map's object collection so it will be rendered onto the map.
map.objects.addAll([istanbul, bucharest]);
// ]]>
</script>
</body>
</html>

How obtain the length of a route?

how can i get the length of a route?
I have been looking at this basic code of a route from a to b:
// Get the DOM node to which we will append the map
var mapContainer = document.getElementById("mapContainer");
// Create a map inside the map container DOM node
var map = new nokia.maps.map.Display(mapContainer, {
// Initial center and zoom level of the map
center: [52.51, 13.4],
zoomLevel: 7,
// We add the behavior component to allow panning / zooming of the map
components:[new nokia.maps.map.component.Behavior()]
}),
router = new nokia.maps.routing.Manager(); // create a route manager;
// The function onRouteCalculated will be called when a route was calculated
var onRouteCalculated = function (observedRouter, key, value) {
if (value == "finished") {
var routes = observedRouter.getRoutes();
//create the default map representation of a route
var mapRoute = new nokia.maps.routing.component.RouteResultSet(routes[0]).container;
map.objects.add(mapRoute);
//Zoom to the bounding box of the route
map.zoomTo(mapRoute.getBoundingBox(), false, "default");
} else if (value == "failed") {
alert("The routing request failed.");
}
};
/* We create on observer on router's "state" property so the above created
* onRouteCalculated we be called once the route is calculated
*/
router.addObserver("state", onRouteCalculated);
// Create waypoints
var waypoints = new nokia.maps.routing.WaypointParameterList();
waypoints.addCoordinate(new nokia.maps.geo.Coordinate(52.51652540955727, 13.380154923889933));
waypoints.addCoordinate(new nokia.maps.geo.Coordinate(52.52114106145058,13.40921934080231));
/* Properties such as type, transportModes, options, trafficMode can be
* specified as second parameter in performing the routing request.
* See for the mode options the "nokia.maps.routing.Mode" section in the developer's guide
*/
var modes = [{
type: "shortest",
transportModes: ["car"],
options: "avoidTollroad",
trafficMode: "default"
}];
// Calculate the route (and call onRouteCalculated afterwards)
router.calculateRoute(waypoints, modes);shortest
When the route is successfully calculated, the call-back function holds an array of one or more routes.
Code:
var routes = observedRouter.getRoutes();
Each of these holds a route summary, where you can obtain useful info about the route.
Code:
alert ("Route Length = " + routes[0].totalLength + " m.");
alert ("As the crow flies = " + routes[0].waypoints[0].mappedPosition.distance(routes[0].waypoints[1].mappedPosition) + " m.");
(Obviously you'll need to use waypoints.length -1 for a calculation with stop-overs)
Here is your code example, with the extra two lines added, You need to use your own app id and token to get it to work.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Example from Nokia Maps API Playground, for more information visit http://api.maps.nokia.com
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9"/>
<base href="http://developer.here.net/apiexplorer/examples/api-for-js/routing/map-with-route-from-a-to-b.html" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Nokia Maps API Example: Add route from A to B</title>
<meta name="description" content="Routing Manager offers the ability to request a route with various modes between two points"/>
<meta name="keywords" content="routing, services, a to b, route, direction, navigation"/>
<!-- For scaling content for mobile devices, setting the viewport to the width of the device-->
<meta name=viewport content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<!-- Styling for example container (NoteContainer & Logger) -->
<link rel="stylesheet" type="text/css" href="http://developer.here.net/apiexplorer/examples/templates/js/exampleHelpers.css"/>
<!-- By default we add ?with=all to load every package available, it's better to change this parameter to your use case. Options ?with=maps|positioning|places|placesdata|directions|datarendering|all -->
<script type="text/javascript" charset="UTF-8" src="http://api.maps.nokia.com/2.2.3/jsl.js?with=all"></script>
<style type="text/css">
html {
overflow:hidden;
}
body {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
height: 100%;
position: absolute;
}
#mapContainer {
width: 100%;
height: 100%;
left: 0;
top: 0;
position: absolute;
}
</style>
</head>
<body>
<div id="mapContainer"></div>
<script type="text/javascript" id="exampleJsSource">
/* Set authentication token and appid
* WARNING: this is a demo-only key
* please register on http://api.developer.nokia.com/
* and obtain your own developer's API key
*/
nokia.Settings.set("appId", "YOUR APP ID");
nokia.Settings.set("authenticationToken", "YOUR TOKEN");
// Get the DOM node to which we will append the map
var mapContainer = document.getElementById("mapContainer");
// Create a map inside the map container DOM node
var map = new nokia.maps.map.Display(mapContainer, {
// Initial center and zoom level of the map
center: [52.51, 13.4],
zoomLevel: 7,
// We add the behavior component to allow panning / zooming of the map
components:[new nokia.maps.map.component.Behavior()]
}),
router = new nokia.maps.routing.Manager(); // create a route manager;
// The function onRouteCalculated will be called when a route was calculated
var onRouteCalculated = function (observedRouter, key, value) {
if (value == "finished") {
var routes = observedRouter.getRoutes();
//create the default map representation of a route
var mapRoute = new nokia.maps.routing.component.RouteResultSet(routes[0]).container;
map.objects.add(mapRoute);
//Zoom to the bounding box of the route
map.zoomTo(mapRoute.getBoundingBox(), false, "default");
alert ("Route Length = " + routes[0].totalLength + " m.");
alert ("As the crow flies = "
routes[0].waypoints[0].mappedPosition.distance(
routes[0].waypoints[1].mappedPosition) + " m.");
} else if (value == "failed") {
alert("The routing request failed.");
}
};
/* We create on observer on router's "state" property so the above created
* onRouteCalculated we be called once the route is calculated
*/
router.addObserver("state", onRouteCalculated);
// Create waypoints
var waypoints = new nokia.maps.routing.WaypointParameterList();
waypoints.addCoordinate(new nokia.maps.geo.Coordinate(52.51652540955727, 13.380154923889933));
waypoints.addCoordinate(new nokia.maps.geo.Coordinate(52.52114106145058, 13.40921934080231));
/* Properties such as type, transportModes, options, trafficMode can be
* specified as second parameter in performing the routing request.
*
* See for the mode options the "nokia.maps.routing.Mode" section in the developer's guide
*/
var modes = [{
type: "shortest",
transportModes: ["car"],
options: "avoidTollroad",
trafficMode: "default"
}];
// Calculate the route (and call onRouteCalculated afterwards)
router.calculateRoute(waypoints, modes);
</script>
</body>
</html>

Categories

Resources