×

Discussion Board

Results 1 to 10 of 10

Thread: HTML5 + KML ?

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    8

    HTML5 + KML ?

    HI

    I would like to display our POI base in KML format on HERE Maps HTML5 for mobile. Is it possible and what is the code that I should add to this one above? Thanks

    Code:
    <!doctype html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0,
    maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet"
    href="http://api.maps.nokia.com/mobile/1.0.2/lib/mh5.css">
    <link rel="stylesheet"
    href="http://api.maps.nokia.com/mobile/1.0.2/lib/colors.css">
    </head>
    <body class="mh5_hwacc_body">
    <script src="http://api.maps.nokia.com/mobile/1.0.2/lib/mh5.js">
    </script>
    <div id="app_location"
    style="width: 320px; height: 480px; position: relative;">
    </div>
    <script>
    nokia.mh5.assetsPath =
    "http://api.maps.nokia.com/mobile/1.0.2/lib/";
    nokia.mh5.app.embed ({
    domNode: "#app_location",
    "appId": " myid ",
    "appCode": " mycode ",
    });
    </script>
    </body>
    </html>nks
    Last edited by jasfox; 2013-05-23 at 15:19.

  2. #2
    Regular Contributor
    Join Date
    Aug 2011
    Location
    Berlin
    Posts
    289

    Re: HTML5 + KML ?

    Yes it is possible but you'll need to add a fair bit of code to get it to work since there is no KML parser embedded within the MH5 framework . The overview page to the framework outlines its basic usage

    The MH5 Framework is a JavaScript framework designed for quick and lightweight creation of location-based mobile web apps. You can easily develop your own native-like applications, that benefit from using Nokia's maps, search, routing, and places services, just like Nokia HTML5 Maps.
    "Quick and lightweight" means it is great at its basic use case where you have a series of POIs in your database and wish to display them on the map, but you need to be more creative if you stray from this basic idea - hence no KML support out of the box.

    Now, assuming you're not planning to read arbitrary KML data from the whole KML specification, it is possible to write a simple KML parser using jquery - there is an example bundled in the KML Generator tool described here. The important bit is copied below:

    Code:
      // Reads the KML text and displays the result on the screen.
      function  parseKml(kml){
            
          // CDATA section can hold HTML and aren't easily parsed by jQuery
          // convert the data within the CDATA section into escaped format so
          // we can read it in as text.
          while ( kml.search ("<!\\[CDATA\\[")  > - 1){
              var from = kml.search ("<!\\[CDATA\\["); 
                var to= kml.search ("\\]\\]>");
                kml = kml.substring(0, from) +  escape(kml.substring(from + 9, to)) +  kml.substring(to+ 3);
      		}
    
          $(kml).dataType =  'xml';
          $(kml).find("Placemark").each(function(){
              // Iterate through all the placemarks, and add Markers or Polylines as necessary.      
              var markerData = new Object();
              var lineData = new Object();
              
              // The Editor associates title with id, but this is optional.
              markerData.title = $(this).attr('id');
              // load the escaped description as text.
        			descCDATA = $(this).find('description').text();
        			if (descCDATA == null){
        				    // If there is no description data, set it blank.
                    markerData.description = "";
    			    } else {
    			    	  // If there is description data, convert it back to HTML.
    			        markerData.description =  unescape(descCDATA);
    			    }
    			    // Read in the name, address and style URL elements.
    			    markerData.name =  $(this).find('name').text();
    			    markerData.address = $(this).find('address').text();
    			    markerData.styleURL = $(this).find('styleUrl').text();
    			    
    			    // Either we have a Point with a coordinate or a LineString with multiple coordinates.
        			var coord = $(this).find('Point').text();
              var coords = $(this).find('LineString').text();
              
             
             $(this).find('Style').each(function(){
             			// If we have an inline style we may have an icon.
             	    var start = $(this).text().search("<href>");
             	    var end =  $(this).text().search("</href>");         	  
             	    if (start > -1 && end > -1 ){
        				      markerData.icon  =  $(this).text().substring(start + 6, end );
        				  }
      				});
                      
        			if ( coord != ""){
                   /// add point - parse the coordinate into longitude and latitude.
                    var lng = coord.substring( 0 , coord.search(","));
                    coord = coord.substring(coord.search(",")+ 1);
                    var lat = coord.substring( 0 , coord.search(","));
                    markerData.coords = new nokia.maps.geo.Coordinate(parseFloat(lat), parseFloat(lng));
                        
                    currentMarker = addMarker(markerData);
                    map.setCenter( markerData.coords);
              }
              if( coords != ""){
                   /// add line  - read each waypoint in with a new line after each one.
                   var waypoints = new Array();
                   var n= 1;
                   do {                                  
    									var lng = coords.substring( 0 , coords.search(","));
    									coords = coords.substring(coords.search(",")+ 1);
    									var lat = coords.substring( 0 , coords.search(","));
    									try {
    									waypoints.push( new nokia.maps.geo.Coordinate(parseFloat(lat), parseFloat(lng))); 
    								} catch(err) {}
    									coords = coords.substring(coords.search("\n")+ 1);
    							} while (coords.search("\n") > -1)
    							
    							// Finally create a Polyline.
    							lineData.waypoints = waypoints ; 
    							lineData.styleURL =  markerData.styleURL;
    							addLine(lineData); 
    					}
          });
      }
    Of course you'll need to alter the marker and polyline generation bits to using addPOI() and so on.

  3. #3
    Registered User
    Join Date
    Mar 2003
    Posts
    8

    Re: HTML5 + KML ?

    Thanks for your fast reply

  4. #4
    Registered User
    Join Date
    Mar 2003
    Posts
    8

    Re: HTML5 + KML ?

    I m wondering is it easier to dispalay .csv coordinates instead of making kml parser? I need something simple just to show markers on specific POIs

  5. #5
    Regular Contributor
    Join Date
    Aug 2011
    Location
    Berlin
    Posts
    289

    Re: HTML5 + KML ?

    Quote Originally Posted by studentproject View Post
    I m wondering is it easier to dispalay .csv coordinates instead of making kml parser?
    Well the standard CSV split function is shorter:
    Code:
    // Standard Library for spliting up Comma Delimited Texts.  
    String.prototype.splitCSV = function(sep) {
    		for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {
    		  if (foo[x].replace(/"\s+$/, '"').charAt(foo[x].length - 1) == '"') {
    		    if ((tl = foo[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) == '"') {
    		      foo[x] = foo[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');
    		    } else if (x) {
    		      foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));
    		    } else foo = foo.shift().split(sep).concat(foo);
    		  } else foo[x].replace(/""/g, '"');
    		} 
    		return foo;
    };
    }());
    It should be simple enough to read in a set of co-ordinates (and less verbose than KML)
    Quote Originally Posted by studentproject View Post
    I need something simple just to show markers on specific POIs
    If you want to keep within the standard use case of the framework, you should look at creating your own custom search component - i.e. host your data on the server side.

  6. #6
    Registered User
    Join Date
    Mar 2003
    Posts
    8

    Re: HTML5 + KML ?

    Can I use Figure 14 from infobuble example 4 (MH5 Framework for Mobile HTML5) to show all .csv data on the map..and to make Infobubles always be shown on the map?
    Can I hide the search box? And adress/chrome bar?

    Thanks

  7. #7
    Regular Contributor
    Join Date
    Aug 2011
    Location
    Berlin
    Posts
    289

    Re: HTML5 + KML ?

    Quote Originally Posted by studentproject View Post
    Can I use Figure 14 from infobubble example 4 (MH5 Framework for Mobile HTML5) to show all .csv data on the map..and to make Infobubbles always be shown on the map?
    Can I hide the search box? And address/chrome bar?

    Thanks
    Two of these questions are easy to answer:
    • Read the configuration section to find out how to remove the search box - just, set the value to null.
    • The infobubble showcase describes how to configure your info bubbles. Obviously if you want to follow one of the examples then the configuration code is available.


    However, I would advise against the combination of read-in-lots-of-data-and-show-infobubbles for all of the POIs - this would overly clutter the relatively small screen of a typical device. It would be much simpler (and lead to a more standard UI) to add markers for each POI an use a standard list view / map with markers + one infobubble on screen.

  8. #8
    Registered User
    Join Date
    Mar 2003
    Posts
    8

    Re: HTML5 + KML ?

    I will follow your advice. So in the message 5 you described me how to display .csv coordinates, would they be automatically displayed as markers all the time on the map or I need to add some more code? Thanks
    Last edited by studentproject; 2013-05-29 at 12:25.

  9. #9
    Regular Contributor
    Join Date
    Aug 2011
    Location
    Berlin
    Posts
    289

    Re: HTML5 + KML ?

    The following code works for me - it uses a proper jQuery function to parse the data and makes sequential calls to map.listeners.ready to firstly read and add the POIs and secondly zoomTo the correct part of the globe.

    Code:
    <!doctype html>
    <html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=100">
        <!-- Definitions of mobile-friendly documents e.g. for BlackBerry: -->
        <meta name="HandheldFriendly" content="True">
        <!-- Definitions of mobile-friendly documents for Microsoft Browser: -->
        <meta name="MobileOptimized" content="width">
        <!-- iOS viewport definitions: -->
        <!--meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"-->
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <!-- disable BlackBerry UI events -->
        <meta name="touch-event-mode" value="native">
        <meta name="cursor-event-mode" value="native">
        <!-- disables address sniffing -->
        <meta name="format-detection" content="telephone=no"/>
        <meta name="format-detection" content="address=no"/>
        <title>CSV Example</title>
    
        <link rel="stylesheet" href="../../lib/mh5.css" type="text/css">
        <link rel="stylesheet" href="../../lib/colors.css" type="text/css">
        <style>
            html, body, #shapes {
                margin: 0;
                padding: 0;
                height: 100%;
            }
        </style>
    </head>
    <body>
    
        <script src="../../lib/mh5.js"></script>
        <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
        <script src="http://jquery-csv.googlecode.com/git/src/jquery.csv.js"></script>
    
        <div id="shapes"></div>
    
        <script type="text/javascript">
            nokia.mh5.assetsPath = "../../lib/";
            nokia.mh5.appId = "YOUR_APP_ID";
            nokia.mh5.appCode = "YOUR_TOKEN";
            
           // AJAX call to read in the data from the specified file.
    	var addPOIfromCSV =	function (filename) {
    		$.ajax({
    			type: "GET",
    			url: filename ,
    			data: null,
    			success: parseCSV,
    		    error : err
    		});
    	}
    	
    	// Error function - useful for debug.
    	function err (){
    			alert("An Error has occurred.");
    	}
    	
           // Actual CSV parsing using the jquery.csv.js library.
    	function parseCSV(csv){
    		var rows =  $.csv.toArrays(csv);
    		// Use this for zoomTo		
    		var ne ={latitude:-90, longitude:180};
    		var sw ={latitude:90, longitude:-180};
    		
    		 // Start from 1 since we have a header row.
    		 for(var i = 1; i < rows.length -1; i += 1) {
               
                  var fields = rows[i]; 
                  map.createPoi( nokia.mh5.assetsPath + "/img/categories/01.icon.mh5.basic.png", {
    					longitude: fields[5],
    					latitude: fields[6],
    					name: fields[1]
    				});
                  
                   ne.latitude = Math.max(fields[6],  ne.latitude);
                   ne.longitude = Math.min(fields[5],  ne.longitude);
                   sw.latitude = Math.min(fields[6],  sw.latitude);
                   sw.longitude = Math.max(fields[5],  sw.longitude);
               } 
               // Once we have the data, we can zoom to.
               map.listeners.ready = function(){map.box = [ne, sw ]};
    	}
    
        // Initialise the map with a callback to load the map data.	
        var map = new nokia.mh5.components.Map({
                schema: "normal.day",
                listeners: {
                	ready : addPOIfromCSV("chinese-cities.csv")
                }
        });
        document.getElementById("shapes").appendChild(map.root);
        </script>
    
    </body>
    </html>
    Of course the example is dependent upon the format of the data, this is a file called chinese-cities.csv, several of the fields are left unused, but are of a deliberately difficult format:
    Code:
    Rank,Chinese Name,English Name,Built-up area,Urban area,longitude,latitude
    1,重庆,Chongqing,"4,802,511","5,402,721",106.55183,29.56256
    2,上海, Shanghai,"25,607,016","22,315,426",121.47489,31.23037
    3,北京,Beijing,"19,980,328","18,827,000",116.40707,39.90468
    4,成都,Chengdu,"6,730,749","7,123,697",104.06478,30.6585
    5,天津,Tianjin,"10,290,987","11,090,314",117.21462,39.12051
    6,广州,Guangzhou,"41,230,000","11,070,654",113.26545,23.12886
    7,保定,Baoding,"1,665,360","1,028,000",115.46458,38.87371
    8,苏州,Suzhou,"4,074,000","4,074,000",120.58291,31.29828
    9,深圳,Shenzhen,"10,357,938","10,357,938",114.05797,22.54273
    10,南阳,Nanyang,"1,672,171","1,672,171",112.5285,32.99099
    11,石家庄,Shijiazhuang,"3,833,606","2,604,930",114.51431,38.04298
    12,临沂,Linyi,"1,876,770","1,876,770",118.35646,35.10452
    13,哈尔滨,Harbin,"5,282,783","4,517,549",126.53586,45.80199
    14,武汉,Wuhan,"6,886,253","6,434,373",114.30542,30.59269
    15,邯郸,Handan,"1,371,399","946,159",114.49363,36.61215
    Now, of course, it would be even easier to display the data if you could create and hold your in JSON format, since JSON is effectively the default standard data type of the JavaScript platform. There are plenty of CSV to JSON convertors out there. Even better would be to follow the standard POI format (with attributes such as address, categoryIcon, latitude, longitude and name ). With minor manipulation, the data set above could come out as follows:

    Code:
    var results = [
    	{
    		"name": "重庆",
    		"address": "Chongqing",
    		"categoryIcon":       "img/marker.png",
    		"longitude": "106.55183",
    		"latitude": "29.56256"
    	},
    	{
    		"name": "上海",
    		"address": "Shanghai",
    		"categoryIcon":       "img/marker.png",
    		"longitude": "121.47489",
    		"latitude": "31.23037"
    	},
    ...etc
    ]
    You would then be able to display the POIs using createPOI() directly.

    So in order of preference I would attempt the following:

    1. For a simple web app with standard search functionality, when I control both the data and the UI:
      • Use the nokia.mh5.app.embed method to create a high-level embedded application
      • Create your own web service which spits out JSON results in the correct POI data format.
      • Override the default SearchAdapater to make the an appropriate webservice request and display the data.

    2. For a simple web app with standard search functionality, when I control the front end only and a JSON feed exists:
      • Use the nokia.mh5.app.embed method to create a high-level embedded application
      • use the existing the web service feed using the JSON endpoint
      • Override the default SearchAdapater to make the an appropriate webservice request to read the data
      • use the Array.map(mapFunction) function to switch from the backend JSON to POI format then display the data.


    3. For a simple web app with standard search functionality, when I control the front end only and webservice feed exists but not in JSON format:
      • Use the nokia.mh5.app.embed method to create a high-level embedded application
      • Override the default SearchAdapater to make the an appropriate webservice request using AJAX calls as in the example above, then map data format received field-by-field into POI format. and display the data.

    4. For a simple web app with standard search functionality, when I control the front end, the data set is small and I do not have an underlying webservice
      • Use the nokia.mh5.app.embed method to create a high-level embedded application
      • Transform my complete array of static data from the original format (e.g. CSV, KML etc) to JSON - preferably the standard POI format.
      • Override the default SearchAdapater to read in the complete dataset and filter it appropriately and use this to display the data.


    Now, if you want more advanced logic in your application - i.e. your use case doesn't follow the logic of the default application flow, you'll need to do the same as the above but by using MH5 components and ui controls instead.
    Last edited by jasfox; 2013-06-11 at 08:56.

  10. #10
    Registered User
    Join Date
    Mar 2003
    Posts
    8

    Re: HTML5 + KML ?

    Thanks for your reply

Similar Threads

  1. Use HTML5 and canvas
    By shinobi86 in forum [Archived] Maps API for Javascript
    Replies: 1
    Last Post: 2013-03-25, 13:27
  2. HTML5 apps..
    By mrrekcuf in forum Nokia N9
    Replies: 4
    Last Post: 2011-09-16, 14:25
  3. html5 onclick
    By Meins in forum Qt
    Replies: 1
    Last Post: 2011-07-07, 10:22

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×