[[topnavbar]]

Nokia Maps API Developer's Guide

[[tabnav]]

Getting Started

The Nokia Maps API for JavaScript is simple to use. At the most basic level, to create a functioning application, you need to:

  1. Load the Maps API JavaScript library file from the HTML page – a <script src> element within the <head> must point to the Maps API library.
  2. Set authentication and authorization credentials – needed for unlimited access to the Nokia Maps API; see also Acquiring API credentials .
  3. Add code implementing your application – write it as code in code in a <script> element in the <body> of the page; as we demonstrate below, it takes only a few lines of code to create a fully functioning application with an interactive map.

We elaborate on these steps below.

Loading the Maps API

To load the Maps API library file, add the following <script> element to the <head> of the HTML document:

<script src="http://api.maps.nokia.com/2.1.1/jsl.js" type="text/javascript" charset="utf-8"/>
						

If you use Microsoft Internet Explorer, you can ensure compatibility by placing this line with a meta tag before any <script> elements in the <head>:

<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9" />
						

And here's is the complete <head> element that loads the Nokia Maps API library and makes sure there is no conflict with IE:

<!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="X-UA-Compatible" content="IE=7; IE=EmulateIE9" />
<script src="http://api.maps.nokia.com/2.1.1/jsl.js" type="text/javascript" charset="utf-8">
</script>
…
</head>
						

The library file jsl.js contains three things:

  • common classes that are always needed, regardless of the module combination
  • a package loader which enables the loading of specific module combinations
  • environment detection code that enables the API to decide on an optimal set of packages for the environment

For more information about loading the library and the available options, please see "Packages and Detection".

Note that if you wish the map to fill the entire window in Internet Explorer 7 or 8, you must set the CSS attributes that control the position and dimensions of the body element as shown in the example below, otherwise map will flicker during panning.

<!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="X-UA-Compatible" content="IE=7; IE=EmulateIE9" />
<style type="text/css">
	html {
		overflow:hidden;
	}
	
	body {
		margin: 0;
		padding: 0;
		position: absolute;
		overflow:hidden;
		width: 100%;
		height: 100%;
	}
	
	#mapContainer {
		width: 100%;
		height: 100%;
		left: 0;
		top: 0;
		position: absolute;
	}
</style>
…
</head>
<body>
<div id="mapContainer"></div>
</body>
</head>		

Acquiring API credentials

Nokia provides several service options within the Maps API offering. In general, the service is free to use, but if you complete our free registration process and obtain authentication and authorization credentials, your application will have priority access to the service and will thus avoid a potential performance penalty. Please read the Location API Business Models and Usage Restrictions page to decide which business model best fits your needs. Authentication requires unique Maps API credentials, namely an "AppId" and a token. You can obtain them from the Nokia Developer API Registration page.

Using API credentials

Having registered your application, set the credentials on the ApplicationContext class, which is part of the utils package of the Maps API. This is, in fact, the first part of the actual implementation of a new application, although it can be seen as an optional step.

The generalized code example below shows how to do this – simply click on the area marked "JavaScript" or "JavaScript + HTML" to view the code.

  •  
    JavaScript
    // Authentication set-up is the first thing that you must do with the API 
    nokia.maps.util.ApplicationContext.set({"appId": "YOUR APPID", "authenticationToken": "YOUR TOKEN"});
    									
  •  
    JavaScript + HTML
    [[exHtmlPart1]]
    // Authentication set up is the first thing that you must do with the API
    nokia.maps.util.ApplicationContext.set({"appId": "YOUR APPID", "authenticationToken": "YOUR TOKEN"});
    [[exHtmlPart2]]
    									

A Basic Map

The simplest application using the Nokia Maps API, is one that displays a non-interactive map with a pre-defined zoom level and center. To implement such an application:

  1. Define a target HTML element in which the map is to be rendered, setting the "id" attribute on it.
  2. Instantiate nokia.maps.map.Display, passing to the constructor the id of the target element, the desired map zoom level and the coordinates of the center of the visible map

Below, you can see both the outcome of implementing this simple scenario and also the code showing how it has been achieved: click on the area marked "JavaScript" or "JavaScript + HTML" to view the code.

A basic non-interactive map

  •  
    JavaScript
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    	'zoomLevel': 10, // Zoom level for the map
    	'center': [52.51, 13.4] // Center coordinates
    });
    									
  •  
    JavaScript + HTML

    [[exHtmlPart1]]
    var map = new nokia.maps.map.Display(
    	document.getElementById("map"), {
    		'zoomLevel': 10, // Zoom level for the map
    		'center': [52.51, 13.4] // Center coordinates
    	}
    );
    [[exHtmlPart2]]
    									

The example above places the map inside a <div> with the id=’map’. Other DOM elements that support nesting can be used as well, for example <span>, <p>, or <em>, but we strongly recommend <div> as the host element for the map for best results.

It is important to bear in mind that most browsers use predefined styles for many DOM elements. To ensure a consistent look and feel in different browsers, you need to apply your own CSS style to the DOM element that displays the map. The code examples shown in this guide demonstrate how to do this in a simple, but effective browser-independent way.

Changing the map type programmatically

The Map API class Display provides constants that represent the available base map types:

NORMAL This is the default base type showing a conventional map
SATELLITE This is a type that offers a view of the map based on satellite imagery
TERRAIN This is a type that shows a map based elevation profile imagery

To set or change the base map type, set the property "baseMapType" on the Display class, using the set() method:

map.set("baseMapType", map.SATELLITE); // Activates satellite imagery on the display
						

A map with the base type "satellite"

  •  
    JavaScript
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    	zoomLevel: 10,
    	center: [52.51, 13.4]
    });
    // Activate satellite imagery on the display
    map.set("baseMapType", map.SATELLITE);
    									
  •  
    JavaScript + HTML
    [[exHtmlPart1]]
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    	zoomLevel: 10,
    	center: [52.51, 13.4]
    });
    // Activate satellite imagery on the display
    map.set("baseMapType", map.SATELLITE);
    [[exHtmlPart2]]
    										

See also the "Map Type" example in the Nokia Maps API Playground.

Components and User Interaction

The Nokia Maps API ships with a basic set of UI components that allow you to build an application around an interactive map. The application user can zoom in or out, pan the map or change its scale, change the map type, etc., via the UI controls offered by these components.

The following UI components are available with the Nokia Maps API:

Behavior A collection of components that enable general user interaction with the map via the mouse or touch (the interaction types include zoom, panning, etc.)
Zoombar A component that provides a zoom slider on the left-hand side of the map, allowing the user to zoom in/out.
Scalebar A component that displays a scale bar at the bottom of the map. The user can expand it to show a large ruler as well as change the units between metric and imperial.
TypeSelector A component that displays a map type switcher in the top right corner of the map.
Positioning A component as part of the positioning package. It provides a button that when clicked or touched will trigger a positioning request and on success center to the user position and show a circle indicating the accuracy of the result.

To use the UI components, you need to add them to the Display instance. The following example shows how to do this:

A map with all components of the Nokia Maps API distribution

  •  
    JavaScript
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    	components: [ 
    		// Behavior collection
    		new nokia.maps.map.component.Behavior(),
    		new nokia.maps.map.component.ZoomBar(),
    		new nokia.maps.map.component.Overview(),
    		new nokia.maps.map.component.TypeSelector(),
    		new nokia.maps.map.component.ScaleBar() ],
    	zoomLevel: 10,
    	center: [52.51, 13.4]
    });
    // Remove zoom.MouseWheel behavior for better page scrolling experience
    map.removeComponent(map.getComponentById("zoom.MouseWheel"));
    									
  •  
    JavaScript + HTML
    [[exHtmlPart1]]
    	var map = new nokia.maps.map.Display(
    		document.getElementById("map"), {
    			components: [ 
    				// Behavior collection
    				new nokia.maps.map.component.Behavior(),
    				new nokia.maps.map.component.ZoomBar(),
    				new nokia.maps.map.component.Overview(),
    				new nokia.maps.map.component.TypeSelector(),
    				new nokia.maps.map.component.ScaleBar() ],
    			zoomLevel: 10,
    			center: [52.51, 13.4]
    		});
    	  // Remove zoom.MouseWheel behavior for better page scrolling experience
    	  map.removeComponent(map.getComponentById("zoom.MouseWheel"));
    [[exHtmlPart2]]
    									

Note that to ensure easy, continuous scrolling of this documentation page, the example disables mouse wheel zooming. It first creates an instance of Display and then removes zoom.Mousewheel, which is a subcomponent of Behavior.

As an alternative to adding the Behavior component at Display instantiation and then removing its subcomponents, consider adding only the subcomponents of Behavior that you need. The following code sample demonstrates this:

var map = new nokia.maps.map.Display(document.getElementById("map"), {
	// Zoom level for the map
	'zoomLevel': 10,
	// Center coordinates
	'center': [52.51, 13.4] 
});

map.addComponent( new nokia.maps.map.component.zoom.DoubleClick());
map.addComponent( new nokia.maps.map.component.panning.Drag());
map.addComponent( new nokia.maps.map.component.panning.Kinetic());
						

See also the example under "Markers" below, where only the DoubleClick zoom and the DragMarker behavior components are enabled during instantiation of the map Display class.

Markers

One of the most common use cases is to show points of interest (POIs) on the map. The Nokia Maps API offers two sorts of markers:

StandardMarker A marker that provides a predefined set of possible properties
Marker A marker that allows you to use a custom image to indicate a point on the map

The following example shows how to add a StandardMarker with a text label.

A map containing a draggable StandardMarker with a short label, with only DoubleClick zooming and marker draggability behaviors enabled

  •  
    JavaScript
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    	components: [
    		  new nokia.maps.map.component.zoom.DoubleClick(),
    		  // Needed for marker drag
    		  new nokia.maps.map.component.objects.DragMarker()],
    		  zoomLevel: 15,
    		  center: [52.51, 13.4]
    	});
    
    // Create a marker and add it to the map
    var marker = new nokia.maps.map.StandardMarker([52.51, 13.4], {
    	text: "Hi!", // Small label
    	draggable: true  // Make the marker draggable
    });
    map.objects.add(marker);
    									
  •  
    JavaScript + HTML
    [[exHtmlPart1]]
    	var map = new nokia.maps.map.Display(
    		document.getElementById("map"), {
    		components: [
    			new nokia.maps.map.component.zoom.DoubleClick(),
    			// Needed for marker drag
    			new nokia.maps.map.component.objects.DragMarker()],
    			zoomLevel: 15,
    			center: [52.51, 13.4]
    		});
    	
    	// Create a marker and add it to the map
    	var marker = new nokia.maps.map.StandardMarker([52.51, 13.4], {
    		text: "Hi!", // Small label
    		draggable: true  // Make the marker draggable
    	});
    	map.objects.add(marker);
    [[exHtmlPart2]]
    									

As you may have realized, the marker not only stays on the map, but you can move it around: click on the marker, hold the mouse button down and move the mouse. The marker moves with the mouse pointer and when you release the mouse button, the marker drops onto the map at a new location. This works on touch devices as well.

The following example shows how to use a custom Marker image as an icon.

A map containing a non-draggable custom Marker with an icon centered above the position defined by the marker's geographical coordinates. The map supports full interaction except for the zoom.MouseWheel behavior.

  •  
    JavaScript
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    	components: [new nokia.maps.map.component.Behavior()],
    	zoomLevel: 13,
    	center: [52.51, 13.4]
    });
    
    map.removeComponent(map.getComponentById("zoom.MouseWheel"));
    
    var marker = new nokia.maps.map.Marker(
    		new nokia.maps.geo.Coordinate(52.51, 13.4),{
    		title: "marker",
    		visibility: true,
    		icon: "[[devguidePath]]/images/pic_marker_house.png",
    		// Offset the top left icon corner so that it's
    		// Centered above the coordinate
    		anchor: new nokia.maps.util.Point(32, 32) 
    	});
    map.objects.add(marker);
    									
  •  
    JavaScript + HTML
    [[exHtmlPart1]]
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    	components: [new nokia.maps.map.component.Behavior()],
    	zoomLevel: 13,
    	center: [52.51, 13.4]
    });
    
    map.removeComponent(map.getComponentById("zoom.MouseWheel"));
    
    var marker = new nokia.maps.map.Marker(
    	new nokia.maps.geo.Coordinate(52.51, 13.4),{
    	title: "marker",
    	visibility: true,
    	icon: "[[devguidePath]]/images/pic_marker_house.png",
    	// Offset the top left icon corner so that it's
    	// Centered above the coordinate
    	anchor: new nokia.maps.util.Point(32, 32) 
    });
    map.objects.add(marker);
    [[exHtmlPart2]]
    									

Geo Objects

The Nokia Maps API provides several different geo shape classes whose instances can be added to the map Display as custom content. The shape classes represent the circle, the rectangle, the polyline and the polygon.

The example below demonstrates how to add a circle to the map.

A map with a Circle shape

  •  
    JavaScript
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    		components: [new nokia.maps.map.component.Behavior()],
    		zoomLevel: 10,
    		center: [52.51, 13.4]
    });
    
    map.removeComponent(map.getComponentById("zoom.MouseWheel"));
    
    map.objects.add(new nokia.maps.map.Circle(
    		// Place the circle center here
    		[52.51, 13.4],
    		// Radius of 8000 meters
    		8000,
    		{
    			color: "#823f",
    			fillColor: "#2387",
    			width: 10
    		}
    ));
    									
  •  
    JavaScript + HTML
    [[exHtmlPart1]]
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    		components: [new nokia.maps.map.component.Behavior()],
    		zoomLevel: 10,
    		center: [52.51, 13.4]
    });
    
    map.removeComponent(map.getComponentById("zoom.MouseWheel"));
    
    map.objects.add(new nokia.maps.map.Circle(
    		// Place the circle center here
    		[52.51, 13.4],
    		// Radius of 8000 meters
    		8000,
    		{
    			color: "#823f",
    			fillColor: "#2387",
    			width: 10
    		}
    ));
    [[exHtmlPart2]]
    									

The above code demonstrates how to add a circle to the map. The first step is to obtain an instance of the Map API's Circle class. The constructor sets the coordinates, radius and formatting for the circle, using JSON syntax.

The use of other shapes is described in the "Geo Shapes" example in the Nokia Maps API Playground.

KML Support

Because creating content on top of a map is time consuming, most developers look to standards to help them transfer content between platforms seamlessly, and typically use KML, which provides data in XML format. For further information, please visit the KML page of the Open Geospatial Consortium.

The KML specification supports a variety of objects, such as place marks, images and polygons. Many of them have their counterparts in the Nokia Maps API landscape. To translate KML objects to Nokia Maps API objects, use the component KMLResultSet, which is part of the kml package. It uses a dedicated Manager class to handle asynchronous loading of KML data either from a text source or from a KML file.

The Nokia Maps API supports the import of KML files and data sets compliant with versions 2.1 and 2.2 of the KML standard. There are only a small number of features that the API does not as yet support, for example, 3D Buildings. The data are, however, interpreted in the best way possible and unsupported features are ignored in the KML data structure.

For information on how to use the KML import in Web applications and how to interact with the KML objects, please look at the KML file format example and the KML hierarchy tree example in the Playground.

Please note that to satisfy the same-domain policy guidelines enforced by modern Web browsers, our example file and the application are hosted in the same domain, otherwise your browser would most likely raise a security exception.

Services

In addition to client-side features, the Nokia Maps API provides access to services such as search and routing.

For example, the search service can be used to list of nearby points of interest, and the routing service calculates and renders a travel route between two or more points.

Each service object takes care of its related network requests, therefore developers need only to create each service object (as required), providing the appropriate initialization parameters.

To understand how to define action handlers for the services, please refer to the articles under the heading "Advanced API Usage".

Search

Search is a vital part of modern Web applications. The relation between geo coordinates and human-readable POI information is essential to provide rich location-based services. This API gives access to Nokia's extensive geo database containing address, POI and place information from all over the world. For example, if you add a custom place in maps.nokia.com it will later become part of the database and can be retrieved with this API .

The entry point is the nokia.maps.search.Manager, which provides four methods to retrieve search results:

reverseGeoCode() Retrieves address information, given a Coordinate object (a point on the map defined in terms of its latitude and longitude).
geoCode() Obtains the coordinates of a location on the basis of an address.
search() Similar to geoCode(), but additionally takes into account POI information, which is also usually echoed as part of the result.
placeSearch() Searches for places; a Place is an object containing the address of a location, but often also other information. For example, for businesses, hotels, or restaurants, this may include contact data, available services, opening times, images, reviews and user ratings, etc. As search results may include a very large number of times, each with a wealth of detail, you may need to limit queries to a certain Proximity around a search center.

The example below demonstrates how to display search results on the map.

A search example (with the Behavior, TypeSelector and ZoomBar components added to the map display)

  •  
    JavaScript
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    	components: [ new nokia.maps.map.component.Behavior(),
    		new nokia.maps.map.component.TypeSelector(),
    		new nokia.maps.map.component.ZoomBar()
    	],
    	center: [52, 17.5]
    });
    		
    map.removeComponent(map.getComponentById("zoom.MouseWheel"));
    
    var SEARCH = new nokia.maps.search.Manager();
    
    SEARCH.addObserver("state", function (observedManager, key, value) {
    	if(value == "finished") {
    		if (observedManager.locations.length > 0) {
    			var rs = (new nokia.maps.search.component.SearchResultSet(observedManager.locations)).container;
    			// Push marker(s) to map
    			map.objects.add(rs);
    			// Zoom to result(s)
    			map.zoomTo(rs.getBoundingBox());
    			// Zoom out if too close 
    			if (map.zoomLevel > 16) {
    				map.set("zoomLevel", 16);
    			}
    		}
    	} else if (value == "failed") {
    		alert("The automatically triggered search request in the Search example failed."); 
    	}
    });
    SEARCH.search("pariser platz berlin", {
    		// Parameters that determine the proximity of the search
    		// Center: new nokia.maps.geo.Coordinate(52.5, 13.3333),
    		// Radius: 1200000
    });
    SEARCH.clear();
    									
  •  
    JavaScript + HTML
    [[exHtmlPart1]]
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    	components: [ new nokia.maps.map.component.Behavior(),
    		new nokia.maps.map.component.TypeSelector(),
    		new nokia.maps.map.component.ZoomBar() 
    	],
    	center: [52, 17.5]
    });
    
    map.removeComponent(map.getComponentById("zoom.MouseWheel"));
    
    var SEARCH = new nokia.maps.search.Manager();
    
    SEARCH.addObserver("state", function (observedManager, key, value) {
    	if(value == "finished") {
    		if (observedManager.locations.length > 0) {
    			var rs = (new nokia.maps.search.component.SearchResultSet(observedManager.locations)).container;
    			// Push marker(s) to map
    			map.objects.add(rs);
    			// Zoom to result(s)
    			map.zoomTo(rs.getBoundingBox());
    			// Zoom out if too close 
    			if (map.zoomLevel > 16) {
    				map.set("zoomLevel", 16);
    			}
    		}
    	} else if (value == "failed") {
    		alert('The automatically triggered search request in the Search example failed.'); 
    	}
    });
    SEARCH.search("pariser platz berlin", {
    		// Parameters that determine the proximity of the search
    		// Center: new nokia.maps.geo.Coordinate(52.5, 13.3333),
    		// Radius: 1200000
    });
    SEARCH.clear();
    [[exHtmlPart2]]
    										

For more information, please check the examples "Searches" and "Observability" in the Nokia Maps API Playground.

Routing

Route planning and navigation are the most commonly used applications of location-based services. With the Maps API, you can calculate optimal routes that match your own calculation criteria, are based on up-to-date maps and take into account real-time traffic information.

A route describes a path between at least two Waypoints, the starting point and the destination, with optional intermediate waypoints in between.

The class nokia.maps.routing.Manager in the API offers the methods calculateRoute() and getRoutes() to help you leverage the routing functionality.

To obtain a route, you need to call calculateRoute(), providing a list of waypoints and other, optional, parameters. The list of waypoints is an array that can contain instances of the classes Coordinate, Place or Location. You can also specify a RoutingMode to define how the route should be calculated. Its properties include:

  • RoutingType – shortest, fastest, scenic, etc., a routing type defines a travel time and distance preference
  • TransportMode – car, pedestrian, public transport, or truck
  • RoutingOptions – avoid toll roads, avoid ferries, etc., a routing option aims to optimize the route
  • TrafficMode – traffic mode is a Boolean indicating whether information on traffic conditions should be taken into consideration

Based on the parameters, routes are calculated and can be retrieved with a call to the method getRoutes(). A route consists of a list of segments between the different waypoints (RouteLegs), connected with Maneuver information, such as the direction in which to travel, and instructions describing the required maneuver. In addition, a graphical representation of the route as a polyline is included so that a the route can be rendered on the map.

The code below is part of the "Routing" example in the Nokia Maps API Playground. The list of waypoints is given as a parameter for the routing manager. The navigation modes are defined in JSON .

A routing example

  •  
    JavaScript
    var map = new nokia.maps.map.Display(document.getElementById("map"), {
    		components: [new nokia.maps.map.component.Behavior()],
    		zoomLevel: 11,
    		center: [50.12, 8.62]
    	}
    );
    
    map.removeComponent(map.getComponentById("zoom.MouseWheel"));
    // Create a route controller
    var router = new nokia.maps.routing.Manager() 
    // Create waypoints
    var waypoints = new nokia.maps.routing.WaypointParameterList();
    waypoints.addCoordinate(
    	new nokia.maps.geo.Coordinate(50.1120423728813, 8.68340740740811)
    );
    waypoints.addCoordinate(
    	new nokia.maps.geo.Coordinate(50.140411376953125, 8.572110176086426)
    );
    var modes = [{
    	type: "shortest",
    	transportModes: ["car"],
    	options: "avoidTollroad",
    	trafficMode: "default"
    }];
    
    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.");
    	}
    };
    
    // Add the observer function to the router's "state" property
    router.addObserver("state", onRouteCalculated);
    
    // Calculate the route (and call onRouteCalculated afterwards)
    router.calculateRoute(waypoints, modes);
    									
  •  
    JavaScript + HTML
    [[exHtmlPart1]]
    var map = new nokia.maps.map.Display(
    	document.getElementById("map"), {
    		components: [new nokia.maps.map.component.Behavior()],
    		zoomLevel: 11,
    		center: [50.12, 8.62]
    	}
    );
    
    map.removeComponent(map.getComponentById("zoom.MouseWheel"));
    // Create a route controller
    var router = new nokia.maps.routing.Manager() 
    // Create waypoints
    var waypoints = new nokia.maps.routing.WaypointParameterList();
    waypoints.addCoordinate(
    	new nokia.maps.geo.Coordinate(50.1120423728813, 8.68340740740811)
    );
    waypoints.addCoordinate(
    	new nokia.maps.geo.Coordinate(50.140411376953125, 8.572110176086426)
    );
    var modes = [{
    	type: "shortest",
    	transportModes: ["car"],
    	options: "avoidTollroad",
    	trafficMode: "default"
    }];
    
    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.");
    	}
    };
    
    // Add the observer function to the router's "state" property
    router.addObserver("state", onRouteCalculated);
    
    // Calculate the route (and call onRouteCalculated afterwards)
    router.calculateRoute(waypoints, modes);
    [[exHtmlPart2]]
    									

Take a look at the full examples in the Nokia Maps API Playground to learn more about defining handlers and using services such as geocoding and search in the Nokia Maps API.

Built-in Positioning

The user's location is one of the key pieces of information in building a Web map application. The Nokia Maps API supports the use of W3C browser positioning, making it easy for an application to use positioning information.

The code example below is part of the "Positioning" example in the Nokia Maps API Playground.
The positioning service manager requests the user's position from the browser and sends the received coordinates to a callback function. The callback function then creates a marker and a circle to illustrate the accuracy of the received position.

Hover with the mouse over the map below to trigger a positioning request.

An example using the W3C geolocation API (only works in browsers that support this functionality). MouseWheel zooming behavior is enabled in this example.

  •  
    JavaScript
    var map = new nokia.maps.map.Display(document.getElementById("mapEx7"), {
    			components: [new nokia.maps.map.component.Behavior()],
    			zoomLevel: 13,
    			center: [52.51, 13.4]
    		}
    );
    
    var mapNode = document.getElementById("map"),
    posInstructionNode = document.getElementById("posInstruction");
    
    if (navigator.geolocation) {
    	var positioning = new nokia.maps.positioning.Manager(),
    	getPos = function () {
    		if (!window._positioningDone) {
    			window._positioningDone = true;
    			ovi.dom.removeEvent(mapNode, "mouseover", getPos, false);
    			posInstructionNode.innerHTML = "A positioning request has been submitted. Please reload the page to trigger a new request.";
    			positioning.getCurrentPosition(
    				function (position) {
    					var coords = position.coords;
    					var marker = new nokia.maps.map.StandardMarker(coords);
    					var accuracyCircle = new nokia.maps.map.Circle(coords, coords.accuracy);
    					map.objects.addAll([accuracyCircle, marker]);
    					map.zoomTo(accuracyCircle.getBoundingBox(), false, "default");
    					if (map.zoomLevel > 16) {
    						// Zoom out if too close 
    						map.set("zoomLevel", 16);
    					}
    				},
    				function (error) {
    					alert('Positioning was not successful.');
    				},
    				{ 
    				// Optional: wait time before failure
    				// Timeout: 15000 
    				}
    			);
    		}
    	};
    	ovi.dom.addEvent(mapNode, "mouseover", getPos, false);
    } else {
    	var innerH = posInstructionNode.innerHTML;
    	innerH = innerH.replace("<i>", "<I>");
    	innerH = innerH.replace("<I>", "<i style='text-decoration: line-through;'>");
    	innerH += "<br/>Your browser doesn't support the W3C geolocation API, <span style='color: red;'>the geolocation part of this example will not work</span>.";
    	posInstructionNode.innerHTML = innerH;
    }
    									
  •  
    JavaScript + HTML
    [[exHtmlPart1]]
    	var map = new nokia.maps.map.Display(document.getElementById("mapEx7"),
    			{
    				components: [new nokia.maps.map.component.Behavior()],
    				zoomLevel: 13,
    				center: [52.51, 13.4]
    			}
    	);
    	
    	var mapNode = document.getElementById("map"),
    	posInstructionNode = document.getElementById("posInstruction");
    	
    	if (navigator.geolocation) {
    		var positioning = new nokia.maps.positioning.Manager(),
    		getPos = function () {
    			if (!window._positioningDone) {
    				window._positioningDone = true;
    				ovi.dom.removeEvent(mapNode, "mouseover", getPos, false);
    				posInstructionNode.innerHTML = "Positioning request was already initiated. Please reload the page if you want to perform another one.";
    				positioning.getCurrentPosition(
    					function (position) {
    						var coords = position.coords;
    						var marker = new nokia.maps.map.StandardMarker(coords);
    						var accuracyCircle = new nokia.maps.map.Circle(coords, coords.accuracy);
    						map.objects.addAll([accuracyCircle, marker]);
    						map.zoomTo(accuracyCircle.getBoundingBox(), false, "default");
    						if (map.zoomLevel > 16) {
    							// Zoom out if too close 
    							map.set("zoomLevel", 16);
    						}
    					},
    					function (error) {
    						alert('Positioning was not successful.');
    					},
    					{ 
    					// Optional: wait time before failure
    					// Timeout: 15000 
    					}
    				);
    			}
    		};
    		ovi.dom.addEvent(mapNode, "mouseover", getPos, false);
    	} else {
    		var innerH = posInstructionNode.innerHTML;
    		innerH = innerH.replace("<i>", "<I>");
    		innerH = innerH.replace("<I>", "<i style='text-decoration: line-through;'>");
    		innerH += "<br/>Your browser doesn't support the W3C geolocation API, <span style='color: red;'>the geolocation part of this example will not work</span>.";
    		posInstructionNode.innerHTML = innerH;
    	}
    [[exHtmlPart2]]
    									

 

[[footer]]