×
Namespaces

Variants
Actions
(Difference between revisions)

HERE Maps API - Find a USA state (simple game on map utilizing reverse geocoding)

From Nokia Developer Wiki
Jump to: navigation, search
jasfox (Talk | contribs)
m (Jasfox - update to 2.2.4)
jasfox (Talk | contribs)
m (Jasfox - link)
 
(11 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Category:Nokia Maps]][[Category:JavaScript]][[Category:Code Snippet]]
+
[[Category:HERE Maps]][[Category:JavaScript]][[Category:Code Examples]]
{{Abstract|A simple map game demonstrating how to used reverse geocoding in Nokia Maps}}
+
{{Abstract|A simple map game demonstrating how to used reverse geocoding in HERE Maps}}
  
{{ArticleMetaData
+
{{ArticleMetaData <!-- v1.2 -->
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
+
|sourcecode=  [https://github.com/heremaps/examples/blob/master/maps_api_for_javascript/demos/find-an-american-state/index.html find-an-american-state.html]
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|devices= Google Chrome, Firefox
 
|devices= Google Chrome, Firefox
Line 9: Line 9:
 
|platform= Web browser
 
|platform= Web browser
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
|dependencies=Nokia Maps 2.2.4
+
|dependencies= HERE Maps 2.5.3
|signing=<!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
+
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
|keywords= Reverse Geocoding, Nokia Maps, JavaScript
+
|keywords= Reverse Geocoding, HERE Maps, JavaScript
|id= <!-- Article Id (Knowledge base articles only) -->
+
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|translated-by= <!-- [[User:XXXX]] -->
 
|translated-by= <!-- [[User:XXXX]] -->
|translated-from-title= <!-- Title only -->  
+
|translated-from-title= <!-- Title only -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
|update-by=[[User:avnee.nathani]]
+
|update-by= [[User:avnee.nathani]]
|update-timestamp=20111231
+
|update-timestamp= 20111231
|creationdate=20110621
+
|creationdate= 20110621
|author=[[User:Maveric]]
+
|author= [[User:Maveric]]
 
}}
 
}}
  
 
{{SeeAlso|
 
{{SeeAlso|
* [http://developer.here.net/javascript_api Nokia Maps API]
+
* [http://developer.here.com/javascript_api HERE Maps API]
* [http://developer.here.net/apiexplorer/examples/api-for-js/events/map-coordinate-on-click.htmll Coordinates on click]
+
* [http://heremaps.github.io/examples/index.html HERE Maps on Github]
* [http://developer.here.net/apiexplorer/examples/api-for-js/places-search/reverse-geocode.html Reverse geocode example]  }}
+
* [http://developer.here.com/apiexplorer/examples/api-for-js/events/map-coordinate-on-click.htmll Coordinates on click]
 +
* [http://developer.here.com/apiexplorer/examples/api-for-js/places-search/reverse-geocode.html Reverse geocode example]  }}
  
 
==Introduction==
 
==Introduction==
Line 42: Line 42:
 
==Prerequisites==
 
==Prerequisites==
  
Nokia Maps API supported web browser (basically any modern web browser)
+
HERE Maps API supported web browser (basically any modern web browser)
  
The example assumes you have already added the Nokia Maps to your web page as explained in the previous article [http://www.developer.nokia.com/Community/Wiki/Nokia_Maps_API_-_Add_Maps_To_Any_Web_Page Add Maps to Any Web Page]
+
The example assumes you have already added the HERE Maps to your web page as explained in the previous article [[HERE Maps API - Add Maps To Any Web Page]]
  
 
==Important note about maps credentials==
 
==Important note about maps credentials==
  
Nokia provides several services options within the Maps API offering. The service is free to use, but you must obtain and use authentication and authorization credentials to use the services.
+
Nokia provides several services options within the Maps API offering. The service is free to use, but you must obtain and use authentication and authorization credentials to use the services.
 
Please read the [http://www.developer.nokia.com/Develop/Maps/Quota/ 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 get these credentials free from the [https://api.developer.nokia.com/ovi-api Nokia Developer API Registration page].
 
Please read the [http://www.developer.nokia.com/Develop/Maps/Quota/ 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 get these credentials free from the [https://api.developer.nokia.com/ovi-api Nokia Developer API Registration page].
  
Line 54: Line 54:
  
 
==Game code==
 
==Game code==
The full HTML and JavaScript for the guessing game can be found below. Remember to add in your own [[How to Obtain Your Own Nokia appID and Token| AppId and Token]] to get it to work.
+
The JavaScript for the guessing game can be found below. Remember to add in your own [[How to Obtain Your Own Nokia appID and Token| AppId and Token]] to get it to work.
 
<code javascript>
 
<code javascript>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
  var statesArray = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut",
<html xmlns="http://www.w3.org/1999/xhtml">
+
    <head>
+
      <title>Nokia Maps game - Locate the states of USA</title>
+
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+
      <script type="text/javascript"
+
            src="http://api.maps.nokia.com/2.2.4/jsl.js" charset="utf-8">
+
        </script>
+
    </head>
+
    <body onload="init()" >
+
 
+
        <div id="map" style="width:80%; height:80%; position: absolute; "></div>
+
+
        <script type="text/javascript">
+
/////////////////////////////////////////////////////////////////////////////////////
+
// 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");
+
 
+
//
+
/////////////////////////////////////////////////////////////////////////////////////
+
+
//Globals
+
+
    var clicked_location = "";
+
    var myContainer;
+
    var searchManager;
+
    var clicked_country;
+
    var clicked_state;
+
    var map;
+
    var statesArray = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut",
+
 
"Delaware","District of Columbia","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas",
 
"Delaware","District of Columbia","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas",
"Kentucky","Louisiana","Maine","Marshall Islands","Maryland",  "Massachusetts","Michigan","Minnesota",
+
"Kentucky","Louisiana","Maine","Maryland",  "Massachusetts","Michigan","Minnesota",
 
"Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico",
 
"Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico",
 
"New York","North Dakota","North Carolina","Ohio","Oklahoma","Oregon","Pennsylvania",    "Rhode Island",
 
"New York","North Dakota","North Carolina","Ohio","Oklahoma","Oregon","Pennsylvania",    "Rhode Island",
 
"South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington",
 
"South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington",
 
"West Virginia","Wisconsin","Wyoming"];
 
"West Virginia","Wisconsin","Wyoming"];
    var stateAbbrev = ["AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA",
 
"KS","KY","LA","ME","MH","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","ND",
 
"NC","OH","OK","OR","PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT","VI","WA","WV","WI","WY"]
 
 
   
 
   
    var correct_answers = 0;
+
var right = 0;
    var wrong_answers = 0;
+
var wrong = 0;
    var randomnumber=Math.floor(Math.random()*51);
+
 
+
map.set("center",  new nokia.maps.geo.Coordinate(42.16, -100.16));
function random_State()
+
map.set("zoomLevel", 3);
{
+
map.set("baseMapType", nokia.maps.map.Display.SATELLITE_PLAIN);
     randomnumber=Math.floor(Math.random()*51);
+
select_random_state();
     alert("DOUBLE CLICK WHERE YOU THINK IS : "+statesArray[randomnumber]);
+
addClickEventListener(map);
 +
</code>
 +
<code javascript>
 +
function select_random_state(){
 +
     randomnumber=Math.floor(Math.random()*50);
 +
     $("#question").text('Find : ' +statesArray[randomnumber]);
 +
}
 +
</code>
 +
<code javascript>
 +
function addClickEventListener(map){
 +
map.addListener("click",function (event){
 +
event.preventDefault();
 +
coordinate = map.pixelToGeo(event.displayX, event.displayY);
 +
map.objects.add(new nokia.maps.map.Marker(coordinate));
 +
nokia.places.search.manager.reverseGeoCode({
 +
latitude: coordinate.latitude,
 +
longitude: coordinate.longitude,
 +
onComplete: processResults
 +
})
 +
});
 
}
 
}
+
</code>
+
<code javascript>
function init()
+
function processResults(data, requestStatus, requestId) {
{
+
if (requestStatus == "OK" ) {
+
if (data.location !== undefined){
    alert("Hello! Welcome to the game. Click OK to start.");
+
var state = data.location.address.state;
+
    // Set the authentication token, which is needed by the web-services to authenticate your application.
+
if (statesArray[randomnumber] == state){
    nokia.maps.util.ApplicationContext.set("authenticationToken", "<Token>");
+
map.objects.clear();
+
select_random_state();
+
$("#answer").text("Correct answer, that was:" + state);
    //map = new nokia.maps.map.Display(document.getElementById("map"), {'zoomLevel':4, 'center':[39.8, 98.57]});   
+
right += 1;
    map = new nokia.maps.map.Display(document.getElementById("map"),
+
    {
+
} else {
              components: [ new nokia.maps.map.component.Behavior(),
+
$("#answer").text("That was:" + state);
                    new nokia.maps.map.component.ZoomBar(),
+
wrong += 1;
                    new nokia.maps.map.component.Overview(),                           
+
}
                    new nokia.maps.map.component.TypeSelector(),    
+
$("#correct_answers").text("Correct:" + right);
                    new nokia.maps.map.component.ScaleBar()],
+
$("#incorrect_answers").text("Wrong:" + wrong);
            'zoomLevel': 4,
+
}
            'center':[48.166667, -100.166667] // Geographical center of the USA
+
}
   
+
    });
+
+
    map.removeComponent(map.getComponentById("zoom.DoubleClick"));
+
    //This will remove the default functionality on the map, where double clicking on it would zoom the map. We need
+
    //to do this to prevent that the user doubleclick would only be registered by the game and not zooming the map.
+
    //We would like to keep the default zoom level. The user will still have the possibility to zoom the map with the
+
    //mouse scroll wheel.
+
+
    map.addListener("click", eventListener);  // add the listener for mouse click
+
+
    map.set("baseMapType", map.NORMAL);
+
+
    random_State();
+
+
    function eventListener(event){
+
        console.log("in EventListener");
+
        event.preventDefault();
+
        clicked_location = map.pixelToGeo(event.displayX, event.displayY);
+
        console.log(clicked_location.toString());
+
        console.log("Adding a Marker there");
+
        add_Marker_where_clicked();
+
    }
+
+
}
+
+
function add_Marker_where_clicked(){
+
    myMarker = new nokia.maps.map.Marker(clicked_location);
+
    map.objects.add(myMarker);
+
    mapStartReverseGeoCode();
+
 
}
 
}
 +
</code>
  
var processResults = function (data, requestStatus, requestId) {
 
                     
 
      if (requestStatus == "OK") {
 
      console.log (data);
 
                            console.log("SEARCH ENDED SUCCESSFULLY");
 
                              console.log(data.location.address.country);
 
                            clicked_country = data.location.address.country;
 
                            console.log(clicked_country);
 
                            clicked_state = data.location.address.state;
 
                            console.log(clicked_state);
 
                            clicked_county = data.location.address.county;
 
                            console.log(clicked_county);
 
                            clicked_district = data.location.address.district;
 
                            console.log(clicked_district);
 
                            show_results();
 
 
                 
 
                } else if(requestStatus == "ERROR") {
 
                        alert("SEARCH FAILED");
 
                }
 
            };
 
 
function mapStartReverseGeoCode(){
 
  
console.log("Reverse geocoding: "+clicked_location.toString());
+
A working example can be found at:
nokia.places.search.manager.reverseGeoCode({
+
latitude: clicked_location.latitude,
+
longitude: clicked_location.longitude,
+
onComplete: processResults
+
});
+
+
}
+
  
function show_results(){
+
http://heremaps.github.io/examples/examples.html#find-an-american-state__index
+
  //   alert("YOU HAD SELECTED: "+clicked_state+" "+clicked_country);
+
+
    if (stateAbbrev[randomnumber] == clicked_state)
+
      {
+
          correct_answers += 1;
+
        alert("That was CORRECT! You got 1 point"+" Correct ones: "+correct_answers+" "+"Wrong ones:"+wrong_answers);
+
      }
+
    else
+
      {
+
          wrong_answers += 1;
+
        alert("That was WRONG! You got 1 point"+" Correct ones: "+correct_answers+" "+"Wrong ones:"+wrong_answers);
+
      }
+
+
random_State();
+
+
}
+
</script>
+
</body>
+
</html>
+
 
+
+
</code>
+
  
==For more on the Nokia Maps API==
+
==For more on the HERE Maps API==
  
Please check out the Nokia Maps API full documentation and API reference here:
+
Please check out the HERE Maps API full documentation and API reference here:
* [http://developer.here.net/javascript_api Nokia Maps API]
+
* [http://developer.here.com/javascript_api HERE Maps API]
  
 
You may also access the interactive API explorer
 
You may also access the interactive API explorer
* [http://developer.here.net/javascript_api_explorer API explorer]
+
* [http://developer.here.com/javascript_api_explorer API explorer]

Latest revision as of 18:38, 20 December 2013

A simple map game demonstrating how to used reverse geocoding in HERE Maps

Article Metadata
Code ExampleTested with
Devices(s): Google Chrome, Firefox
Compatibility
Platform(s): Web browser
Dependencies: HERE Maps 2.5.3
Article
Keywords: Reverse Geocoding, HERE Maps, JavaScript
Created: Maveric (21 Jun 2011)
Updated: avnee.nathani (31 Dec 2011)
Last edited: jasfox (20 Dec 2013)

Contents

[edit] Introduction

This simple game will introduce how to use the map Event listener for user map clicks, how to find the geocoordinate under the clicked mouse point and how to further use the coordinates to perform a nokia.places.search.manager.reverseGeoCode() search - all this in a form of a guessing game.

Find-a-us-state.png

Feel free to modify and further implement your own version of this game.

[edit] Prerequisites

HERE Maps API supported web browser (basically any modern web browser)

The example assumes you have already added the HERE Maps to your web page as explained in the previous article HERE Maps API - Add Maps To Any Web Page

[edit] Important note about maps credentials

Nokia provides several services options within the Maps API offering. The service is free to use, but you must obtain and use authentication and authorization credentials to use the services. 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 get these credentials free from the Nokia Developer API Registration page.

In the code example below is all required HTML and embedded JavaScript, a full functional application.

[edit] Game code

The JavaScript for the guessing game can be found below. Remember to add in your own AppId and Token to get it to work.

 var statesArray = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut",
"Delaware","District of Columbia","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas",
"Kentucky","Louisiana","Maine","Maryland", "Massachusetts","Michigan","Minnesota",
"Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico",
"New York","North Dakota","North Carolina","Ohio","Oklahoma","Oregon","Pennsylvania", "Rhode Island",
"South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington",
"West Virginia","Wisconsin","Wyoming"];
 
var right = 0;
var wrong = 0;
 
map.set("center", new nokia.maps.geo.Coordinate(42.16, -100.16));
map.set("zoomLevel", 3);
map.set("baseMapType", nokia.maps.map.Display.SATELLITE_PLAIN);
select_random_state();
addClickEventListener(map);
function select_random_state(){
randomnumber=Math.floor(Math.random()*50);
$("#question").text('Find : ' +statesArray[randomnumber]);
}
function addClickEventListener(map){
map.addListener("click",function (event){
event.preventDefault();
coordinate = map.pixelToGeo(event.displayX, event.displayY);
map.objects.add(new nokia.maps.map.Marker(coordinate));
nokia.places.search.manager.reverseGeoCode({
latitude: coordinate.latitude,
longitude: coordinate.longitude,
onComplete: processResults
})
});
}
function processResults(data, requestStatus, requestId) {	
if (requestStatus == "OK" ) {
if (data.location !== undefined){
var state = data.location.address.state;
 
if (statesArray[randomnumber] == state){
map.objects.clear();
select_random_state();
$("#answer").text("Correct answer, that was:" + state);
right += 1;
 
} else {
$("#answer").text("That was:" + state);
wrong += 1;
}
$("#correct_answers").text("Correct:" + right);
$("#incorrect_answers").text("Wrong:" + wrong);
}
}
}


A working example can be found at:

http://heremaps.github.io/examples/examples.html#find-an-american-state__index

[edit] For more on the HERE Maps API

Please check out the HERE Maps API full documentation and API reference here:

You may also access the interactive API explorer

This page was last modified on 20 December 2013, at 18:38.
380 page views in the last 30 days.
×