def createErrorHtml(self): logging.debug(">>") content = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> <head> </head> <body> No Gpx Data </body> </html> ''' file = fileUtils(self.htmlfile,content) file.run() logging.debug("<<")
def createErrorHtml(self,errMsg=None): logging.debug(">>") errMsg = errMsg or '' # convert None to empty string content = ''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> <body> No GPX Data (''' + str(errMsg) + ''') </body> </html> ''' file = fileUtils(self.htmlfile,content) file.run() logging.debug("<<")
def createErrorHtml(self): logging.debug(">>") htmlfile = "%s/error.html" % (self.pytrainer_main.profile.tmpdir) content = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> <head> <body> No HTML file supplied to display </body> </html> ''' file = fileUtils(htmlfile,content) file.run() logging.debug("<<") return htmlfile
def createErrorHtml(self): logging.debug(">>") htmlfile = "%s/error.html" % (self.pytrainer_main.profile.tmpdir) content = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> <head> <body> No HTML file supplied to display </body> </html> ''' file = fileUtils(htmlfile, content) file.run() logging.debug("<<") return htmlfile
def createHtml_osm(self, polyline, startinfo, finishinfo, laps, attrlist, linetype): ''' Generate OSM map html file using MapLayers ''' logging.debug(">>") # try using local cached versions of JS files for faster rendering self.cacheUrls(); content = '''<html> <head> <!-- bring in the OpenLayers javascript library (here we bring it from the remote site, but you could easily serve up this javascript yourself) --> <script src="''' + self.URLS['OpenLayers.js'] + '''"></script> <!-- bring in the OpenStreetMap OpenLayers layers. Using this hosted file will make sure we are kept up to date with any necessary changes --> <script src="''' + self.URLS['OpenStreetMap.js'] + '''"></script> <script type="text/javascript"> //complex object of type OpenLayers.Map var map; //icons data object var icons = { iconSize : new OpenLayers.Size(30,30)''' # If have laps data insert markers here try: lapsContent='' for lap in laps[:500]: # OpenLayers with firefox is limited to 500 markers -> TODO: Transfer to a constant somewhere ? lapNumber = int(lap['lap_number'])+1 elapsedTime = float(lap['elapsed_time']) elapsedTimeHours = int(elapsedTime/3600) elapsedTimeMins = int((elapsedTime - (elapsedTimeHours * 3600)) / 60) elapsedTimeSecs = elapsedTime - (elapsedTimeHours * 3600) - (elapsedTimeMins * 60) if elapsedTimeHours > 0: strElapsedTime = "%0.0dh:%0.2dm:%0.2fs" % (elapsedTimeHours, elapsedTimeMins, elapsedTimeSecs) elif elapsedTimeMins > 0: strElapsedTime = "%0.0dm:%0.2fs" % (elapsedTimeMins, elapsedTimeSecs) else: strElapsedTime = "%0.0fs" % (elapsedTimeSecs) #process lat and lon for this lap lapLat = float(lap['end_lat']) lapLon = float(lap['end_lon']) #build laps content string lapsContent+=',\n' lapsContent+='\t\t\t\t\tlap%d: { url : "/waypoint.png", coordinates : [%f,%f], popupInfo: "%s" }' % \ (lapNumber, lapLon, lapLat, \ "<div class='info_content'>End of lap:%d<br>Elapsed time:%s<br>Distance:%0.2f km<br>Calories:%s</div>" % \ (lapNumber, strElapsedTime, float(lap['distance'])/1000, lap['calories']) ) content+=lapsContent except Exception as e: # If something breaks here just skip laps data logging.error('Error formating laps data: ' + str(e)) # Insert start/finish track markers content+=''',\n start : { url : "/start.png", coordinates : %s, popupInfo : "%s" }, finish : { url : "/finish.png", coordinates : %s, popupInfo : "%s" }, url : "file://%s/glade"''' \ % (polyline[0], startinfo, polyline[-1], finishinfo, os.path.abspath(self.data_path)) content+='''};\n function init() { // fool openlayers scripts so it will download images and themes from the web instead of local folder if cached OpenLayers.ImgPath="''' + self.staticURLS['OpenLayers'] + '''img/"; OpenLayers.scriptLocation="''' + self.staticURLS['OpenLayers'] + '''"; OpenLayers._getScriptLocation=function() { return "''' + self.staticURLS['OpenLayers'] + '''";}; // for transforming WGS 1984 to Spherical Mercator Projection pWGS = new OpenLayers.Projection("EPSG:4326"); pMP = new OpenLayers.Projection("EPSG:900913"); map = new OpenLayers.Map ("map", { controls:[ new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Attribution()], maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34), maxResolution: 156543.0399, numZoomLevels: 19, units: 'm', projection: pMP, displayProjection: pWGS } ); // Track painting style var trackStyle = { strokeColor: "#33DDDD", strokeWidth: 3, strokeDashstyle: "solid", strokeOpacity: 0.6, pointRadius: 6, }; //Build track object var track = { "type":"Feature", "id":"OpenLayers.Feature.Vector_259", "properties":{}, "geometry": { "type":"LineString", "coordinates": [''' #Insert track points here content+=",".join(polyline); content+='''] }, "crs": { "type":"OGC", "properties": { "urn":"urn:ogc:def:crs:OGC:1.3:CRS84" } } } //Add open street maps layers layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik"); map.addLayer(layerMapnik); //Create vector layer to add the data on to var vector_layer = new OpenLayers.Layer.Vector(); vector_layer.setName('Track'); var geojson_format = new OpenLayers.Format.GeoJSON(); var feature = geojson_format.read(track,"Feature"); // transform from WGS 1984 to Spherical Mercator Projection feature.geometry.transform(pWGS, pMP); feature.geometry.calculateBounds(); var vector=new OpenLayers.Feature.Vector(); vector.geometry = feature.geometry; vector.style=trackStyle; vector_layer.addFeatures(vector); map.addLayer(vector_layer); // Insert start/finish markers layerMarkers = new OpenLayers.Layer.Markers("Markers"); var offset = new OpenLayers.Pixel(-(icons.iconSize.w/2), -icons.iconSize.h); for (var i in icons) { if (icons[i].coordinates) { icons[i].icon = new OpenLayers.Icon(icons.url + icons[i].url,icons.iconSize,offset); icons[i].lonLat = new OpenLayers.LonLat(icons[i].coordinates[0],icons[i].coordinates[1]); icons[i].lonLat.transform(pWGS,pMP); icons[i].marker = new OpenLayers.Marker(icons[i].lonLat,icons[i].icon); icons[i].popup = new OpenLayers.Popup.FramedCloud("Info", icons[i].lonLat, null, icons[i].popupInfo, icons[i].icon, true, null ); icons[i].onClick = function(e) { map.addPopup(this.popup); this.popup.show(); } icons[i].marker.events.register("mousedown", icons[i], function(e) { this.onClick(e)} ) layerMarkers.addMarker(icons[i].marker); } } map.addLayer(layerMarkers); //zoom and center to the track layouts map.zoomToExtent(feature.geometry.getBounds()); } </script> </head> <!-- body.onload is called once the page is loaded (call the 'init' function) --> <body onload="init();"> <!-- define a DIV into which the map will appear. Make it take up the whole window --> <div style="width:100%; height:100%" id="map"></div> </body> </html> ''' file = fileUtils(self.htmlfile,content) file.run() logging.debug("<<")
def selectArea(self,dc=None): # try using local cached versions of JS files for faster rendering self.cacheUrls(); content = ''' <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="../theme/default/style.css" type="text/css" /> <link rel="stylesheet" href="style.css" type="text/css" /> <style type="text/css"> p { width: 512px; } #config { margin-top: 1em; width: 512px; position: relative; height: 8em; } #controls { padding-left: 2em; margin-left: 0; width: 12em; } #controls li { padding-top: 0.5em; list-style: none; } #options { font-size: 1em; top: 0; margin-left: 15em; position: absolute; } /* avoid pink tiles */ .olImageLoadError { background-color: transparent !important; } </style> <!-- Load libraries from remote or local cache --> <script src="''' + self.URLS['OpenLayers.js'] + '''"></script> <script src="''' + self.URLS['OpenStreetMap.js'] + '''"></script> <script type="text/javascript"> var map, polygonControl; function init(){ //"fix" locations OpenLayers.ImgPath="''' + self.staticURLS['OpenLayers'] + '''img/"; OpenLayers.scriptLocation="''' + self.staticURLS['OpenLayers'] + '''"; OpenLayers._getScriptLocation=function() { return "''' + self.staticURLS['OpenLayers'] + '''";}; // for transforming WGS 1984 to Spherical Mercator Projection pWGS = new OpenLayers.Projection("EPSG:4326"); pMP = new OpenLayers.Projection("EPSG:900913"); map = new OpenLayers.Map ("map", { controls:[ new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Attribution(), new OpenLayers.Control.MousePosition()], maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34), maxResolution: 156543.0399, numZoomLevels: 19, units: 'm', projection: pMP, displayProjection: pWGS } ); //Add open street maps layers layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik"); map.addLayer(layerMapnik); //Add polygon drawing layer var polygonLayer = new OpenLayers.Layer.Vector("Polygon Layer"); map.addLayer(polygonLayer); polyOptions = {sides: 4, irregular: true}; polygonControl = new OpenLayers.Control.DrawFeature(polygonLayer, OpenLayers.Handler.RegularPolygon, {handlerOptions: polyOptions}); // For desrializings var out_options = { 'internalProjection': map.baseLayer.projection, 'externalProjection': pWGS }; // allow only one feature to be drawn polygonLayer.events.register("beforefeatureadded", polygonLayer, function(f) { polygonLayer.removeAllFeatures(true)}); // Change title after draw polygonLayer.events.register("featureadded", polygonLayer, function(f) { var title=(new OpenLayers.Format.GeoJSON(out_options).write(f.feature,false)); document.title=title; }); //prepaint saved polygon savedPolygon = \'''' + str(self.waypoint) + '''\'; if ((savedPolygon) && (savedPolygon!=='None')) { // deserialize var geojson_format = new OpenLayers.Format.GeoJSON(out_options); var feature = geojson_format.read(savedPolygon); // make sure it's an array if(feature.constructor != Array) feature = [feature]; if (feature && feature.length>0) { var bounds = feature[0].geometry.getBounds(); polygonLayer.addFeatures(feature); map.zoomToExtent(bounds); } } else { map.setCenter(new OpenLayers.LonLat(0, 0), 3); } map.addControl(polygonControl); document.getElementById('noneToggle').checked = true; } function setOptions(options) { polygonControl.handler.setOptions(options); } function setSize(fraction) { var radius = fraction * map.getExtent().getHeight(); polygonControl.handler.setOptions({radius: radius, angle: 0}); } </script> </head> <body onload="init()"> <input type="radio" name="type" value="none" id="noneToggle" onclick="polygonControl.deactivate()" checked="checked" /> <label for="noneToggle">Navigate</label> <input type="radio" name="type" value="polygon" id="polygonToggle" onclick="polygonControl.activate()" /> <label for="polygonToggle">Draw polygon</label> <div id="map" class="smallmap"></div> </body> </html>''' file = fileUtils(self.htmlfile,content) file.run() return self.htmlfile
def createHtml_api3(self,polyline, minlat, minlon, maxlat, maxlon, startinfo, finishinfo, laps, linetype): ''' Generate a Google maps html file using the v3 api documentation at http://code.google.com/apis/maps/documentation/v3 ''' logging.debug(">>") if self.waypoint is not None: waypoints = self.waypoint.getAllWaypoints() #TODO waypoints not supported in this function yet #TODO sort polyline encoding (not supported in v3?) #TODO check http://code.google.com/apis/maps/documentation/v3/overlays.html#Polylines for MVArray?? content = ''' <html> <head> <style type="text/css"> div.info_content { font-family: sans-serif; font-size: 10px; } </style> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> function initialize() {\n''' content += " var startlatlng = %s ;\n" % (polyline[0][0]) content += " var centerlatlng = new google.maps.LatLng(%f, %f);\n" % ((minlat+maxlat)/2., (minlon+maxlon)/2.) content += " var endlatlng = %s;\n" % (polyline[-1][0]) content += " var swlatlng = new google.maps.LatLng(%f, %f);\n" % (minlat,minlon) content += " var nelatlng = new google.maps.LatLng(%f, %f);\n" % (maxlat,maxlon) content += " var startcontent = \"%s\";\n" % (startinfo) content += " var finishcontent = \"%s\";\n" % (finishinfo) content += " var startimageloc = \"%s/glade/start.png\";\n" % (os.path.abspath(self.data_path)) content += " var finishimageloc = \"%s/glade/finish.png\";\n" % (os.path.abspath(self.data_path)) content += " var lapimageloc = \"%s/glade/waypoint.png\";\n" % (os.path.abspath(self.data_path)) content +=''' var myOptions = { zoom: 8, center: centerlatlng, scaleControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP }; var startimage = new google.maps.MarkerImage(startimageloc,\n // This marker is 32 pixels wide by 32 pixels tall. new google.maps.Size(32, 32), // The origin for this image is 0,0. new google.maps.Point(0,0), // The anchor for this image is the base of the flagpole new google.maps.Point(16, 32));\n\n var finishimage = new google.maps.MarkerImage(finishimageloc,\n // This marker is 32 pixels wide by 32 pixels tall. new google.maps.Size(32, 32), // The origin for this image is 0,0. new google.maps.Point(0,0), // The anchor for this image is the base of the flagpole new google.maps.Point(16, 32));\n var lapimage = new google.maps.MarkerImage(lapimageloc,\n // This marker is 32 pixels wide by 32 pixels tall. new google.maps.Size(32, 32), // The origin for this image is 0,0. new google.maps.Point(0,0), // The anchor for this image is the base of the flagpole new google.maps.Point(16, 32));\n var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var startmarker = new google.maps.Marker({ position: startlatlng, map: map, icon: startimage, title:"Start"}); var finishmarker = new google.maps.Marker({ position: endlatlng, icon: finishimage, map: map, title:"End"}); \n //Add an infowindows var startinfo = new google.maps.InfoWindow({ content: startcontent }); var finishinfo = new google.maps.InfoWindow({ content: finishcontent }); google.maps.event.addListener(startmarker, 'click', function() { startinfo.open(map,startmarker); }); google.maps.event.addListener(finishmarker, 'click', function() { finishinfo.open(map,finishmarker); });\n''' #"id_lap, record, elapsed_time, distance, start_lat, start_lon, end_lat, end_lon, calories, lap_number", for lap in laps: lapNumber = int(lap['lap_number'])+1 elapsedTime = float(lap['elapsed_time']) elapsedTimeHours = int(elapsedTime/3600) elapsedTimeMins = int((elapsedTime - (elapsedTimeHours * 3600)) / 60) elapsedTimeSecs = elapsedTime - (elapsedTimeHours * 3600) - (elapsedTimeMins * 60) if elapsedTimeHours > 0: strElapsedTime = "%0.0dh:%0.2dm:%0.2fs" % (elapsedTimeHours, elapsedTimeMins, elapsedTimeSecs) elif elapsedTimeMins > 0: strElapsedTime = "%0.0dm:%0.2fs" % (elapsedTimeMins, elapsedTimeSecs) else: strElapsedTime = "%0.0fs" % (elapsedTimeSecs) #process lat and lon for this lap try: lapLat = float(lap['end_lat']) lapLon = float(lap['end_lon']) content += "var lap%dmarker = new google.maps.Marker({position: new google.maps.LatLng(%f, %f), icon: lapimage, map: map, title:\"Lap%d\"}); \n " % (lapNumber, lapLat, lapLon, lapNumber) content += "var lap%d = new google.maps.InfoWindow({content: \"<div class='info_content'>End of lap:%s<br>Elapsed time:%s<br>Distance:%0.2f km<br>Calories:%s</div>\" });\n" % (lapNumber, lapNumber, strElapsedTime, float(lap['distance'])/1000, lap['calories']) content += "google.maps.event.addListener(lap%dmarker, 'click', function() { lap%d.open(map,lap%dmarker); });\n" % (lapNumber,lapNumber,lapNumber) except Exception as e: #Error processing lap lat or lon #dont show this lap logging.debug( "Error processing lap "+ str(lap) ) logging.debug(str(e)) content += ''' var boundsBox = new google.maps.LatLngBounds(swlatlng, nelatlng );\n map.fitBounds(boundsBox);\n''' pre = 0 for point in polyline: if pre: content += '''var polylineCoordinates = [\n''' content += " %s,\n" % (pre[0]) content += " %s,\n" % (point[0]) content += ''' ];\n // Add a polyline.\n var polyline = new google.maps.Polyline({\n path: polylineCoordinates,\n strokeColor: \"%s\",\n strokeOpacity: 0.9,\n strokeWeight: 5,\n });\n polyline.setMap(map);\n''' % point[2] contenttemplate = [ "%s", "Speed: %0.1f km/h", "HR: %d bpm", "Cadence: %d", ] content += ''' google.maps.event.addListener(polyline, 'click', function(event) { var marker = new google.maps.InfoWindow({ position: event.latLng, content: "%s" }); marker.setMap(map); }); ''' % contenttemplate[linetype] % point[1] pre = point content += ''' } </script> </head> <body onload="initialize()"> <div id="map_canvas" style="width:100%; height:100%"></div> </body> </html>''' file = fileUtils(self.htmlfile,content) file.run() logging.debug("<<")
def createHtml(self,default_waypoint=None): logging.debug(">>") tmpdir = self.pytrainer_main.profile.tmpdir filename = tmpdir+"/waypointeditor.html" points = self.waypoint.getAllWaypoints() londef = 0 latdef = 0 content = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>edit waypoints</title> <script id="googleapiimport" src="http://maps.google.com/maps?file=api&v=2" type="text/javascript"></script> <script type="text/javascript"> """ i = 0 arrayjs = "" if default_waypoint is None and points: default_waypoint = points[0][0] for point in points: if point[0] == default_waypoint: londef = point[2] latdef = point[1] content += "lon = '%f';\n"%point[2] content += "lat = '%f';\n"%point[1] content += "name = '%s';\n"%point[6] content += "description = '%s';\n"%point[4] content += "sym = '%s';\n"%point[7] content += "id = '%d';\n"%point[0] content += """waypoint%d = Array (lon,lat,name,description,sym,id);\n"""%i if i>0: arrayjs+="," arrayjs +="waypoint%d"%i i = i+1 content += """waypointList = Array (%s);\n""" %arrayjs content += """ is_addmode = 0; //<![CDATA[ function addWaypoint(lon,lat) { document.title = "call:addWaypoint(" + lon + "," + lat + ")"; } function updateWaypoint(lon,lat,id) { document.title = "call:updateWaypoint(" + lon + "," + lat + "," + id + ")"; } function createMarker(waypoint) { var lon = waypoint[0]; var lat = waypoint[1]; var id = waypoint[5]; var sym = waypoint[4]; var point = new GLatLng(lat,lon); var text = "<b>"+waypoint[2]+"</b><br/>"+waypoint[3]; var icon = new GIcon(); if (sym=="Summit") { icon.image = \""""+os.path.abspath(self.data_path)+"""/glade/summit.png\"; } else { icon.image = \""""+os.path.abspath(self.data_path)+"""/glade/waypoint.png\"; } icon.iconSize = new GSize(32, 32); icon.iconAnchor = new GPoint(16, 16); icon.infoWindowAnchor = new GPoint(5, 1); var markerD = new GMarker(point, {icon:icon, draggable: true}); map.addOverlay(markerD); markerD.enableDragging(); GEvent.addListener(markerD, "mouseup", function(){ position = markerD.getPoint(); updateWaypoint(position.lng(),position.lat(),id); }); return markerD; } function load() { if (GBrowserIsCompatible()) { //Dibujamos el mapa map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.addControl(new GScaleControl()); """ if londef != 0: content +=""" lon = %s; lat = %s; """ %(londef,latdef) else: content += """ lon = 0; lat = 0; """ content +=""" map.setCenter(new GLatLng(lat, lon), 11); //Dibujamos el minimapa ovMap=new GOverviewMapControl(); map.addControl(ovMap); mini=ovMap.getOverviewMap(); //Dibujamos los waypoints for (i=0; i<waypointList.length; i++){ createMarker(waypointList[i]); map.enableDragging(); } //Preparamos los eventos para anadir nuevos waypoints GEvent.addListener(map, "click", function(marker, point) { if (is_addmode==1){ map.enableDragging(); //map.addOverlay(new GMarker(point)); var lon = point.lng(); var lat = point.lat(); var waypoint_id = addWaypoint(lon,lat); var waypoint = Array (lon,lat,"","","",waypoint_id); createMarker(waypoint); is_addmode = 0; } }); } } function addmode(){ is_addmode = 1; map.disableDragging(); } //]]> </script> <style> .form { position: absolute; top: 200px; left: 300px; background: #ffffff; } </style> </head> <body onload="load()" onunload="GUnload()" style="cursor:crosshair" border=0> <div id="map" style="width: 100%; height: 460px; top: 0px; left: 0px"></div> <div id="addButton" style="position: absolute; top: 32px;left: 86px;"> <input type="button" value="New Waypoint" onclick="javascript:addmode();"> </div> </body> </html> """ file = fileUtils(filename,content) file.run() logging.debug("<<")
def createHtml(self, default_waypoint=None): logging.debug(">>") tmpdir = self.pytrainer_main.profile.tmpdir filename = tmpdir + "/waypointeditor.html" points = self.waypoint.getAllWaypoints() londef = 0 latdef = 0 content = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>edit waypoints</title> <script id="googleapiimport" src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script> <script type="text/javascript"> """ i = 0 arrayjs = "" if default_waypoint is None and points: default_waypoint = points[0][0] for point in points: if point[0] == default_waypoint: londef = point[2] latdef = point[1] content += "lon = '%f';\n" % point[2] content += "lat = '%f';\n" % point[1] content += "name = '%s';\n" % point[6] content += "description = '%s';\n" % point[4] content += "sym = '%s';\n" % point[7] content += "id = '%d';\n" % point[0] content += """waypoint%d = Array (lon,lat,name,description,sym,id);\n""" % i if i > 0: arrayjs += "," arrayjs += "waypoint%d" % i i = i + 1 content += """waypointList = Array (%s);\n""" % arrayjs content += """ is_addmode = 0; //<![CDATA[ function addWaypoint(lon,lat) { document.title = "call:addWaypoint(" + lon + "," + lat + ")"; } function updateWaypoint(lon,lat,id) { document.title = "call:updateWaypoint(" + lon + "," + lat + "," + id + ")"; } function createMarker(waypoint) { var lon = waypoint[0]; var lat = waypoint[1]; var id = waypoint[5]; var sym = waypoint[4]; var point = new GLatLng(lat,lon); var text = "<b>"+waypoint[2]+"</b><br/>"+waypoint[3]; var icon = new GIcon(); if (sym=="Summit") { icon.image = \"""" + os.path.abspath( self.data_path) + """/glade/summit.png\"; } else { icon.image = \"""" + os.path.abspath( self.data_path) + """/glade/waypoint.png\"; } icon.iconSize = new GSize(32, 32); icon.iconAnchor = new GPoint(16, 16); icon.infoWindowAnchor = new GPoint(5, 1); var markerD = new GMarker(point, {icon:icon, draggable: true}); map.addOverlay(markerD); markerD.enableDragging(); GEvent.addListener(markerD, "mouseup", function(){ position = markerD.getPoint(); updateWaypoint(position.lng(),position.lat(),id); }); return markerD; } function load() { if (GBrowserIsCompatible()) { //Dibujamos el mapa map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.addControl(new GScaleControl()); """ if londef != 0: content += """ lon = %s; lat = %s; """ % (londef, latdef) else: content += """ lon = 0; lat = 0; """ content += """ map.setCenter(new GLatLng(lat, lon), 11); //Dibujamos el minimapa ovMap=new GOverviewMapControl(); map.addControl(ovMap); mini=ovMap.getOverviewMap(); //Dibujamos los waypoints for (i=0; i<waypointList.length; i++){ createMarker(waypointList[i]); map.enableDragging(); } //Preparamos los eventos para anadir nuevos waypoints GEvent.addListener(map, "click", function(marker, point) { if (is_addmode==1){ map.enableDragging(); //map.addOverlay(new GMarker(point)); var lon = point.lng(); var lat = point.lat(); var waypoint_id = addWaypoint(lon,lat); var waypoint = Array (lon,lat,"","","",waypoint_id); createMarker(waypoint); is_addmode = 0; } }); } } function addmode(){ is_addmode = 1; map.disableDragging(); } //]]> </script> <style> .form { position: absolute; top: 200px; left: 300px; background: #ffffff; } </style> </head> <body onload="load()" onunload="GUnload()" style="cursor:crosshair" border=0> <div id="map" style="width: 100%; height: 460px; top: 0px; left: 0px"></div> <div id="addButton" style="position: absolute; top: 32px;left: 86px;"> <input type="button" value="New Waypoint" onclick="javascript:addmode();"> </div> </body> </html> """ file = fileUtils(filename, content) file.run() logging.debug("<<")
def createHtml_osm(self, polyline, startinfo, finishinfo, laps, attrlist, linetype): ''' Generate OSM map html file using MapLayers ''' logging.debug(">>") # try using local cached versions of JS files for faster rendering self.cacheUrls(); content = '''<html> <head> <!-- bring in the OpenLayers javascript library (here we bring it from the remote site, but you could easily serve up this javascript yourself) --> <script src="''' + self.URLS['OpenLayers.js'] + '''"></script> <!-- bring in the OpenStreetMap OpenLayers layers. Using this hosted file will make sure we are kept up to date with any necessary changes --> <script src="''' + self.URLS['OpenStreetMap.js'] + '''"></script> <script type="text/javascript"> //complex object of type OpenLayers.Map var map; //icons data object var icons = { iconSize : new OpenLayers.Size(30,30)''' # If have laps data insert markers here try: lapsContent='' for lap in laps[:500]: # OpenLayers with firefox is limited to 500 markers -> TODO: Transfer to a constant somewhere ? lapNumber = int(lap['lap_number'])+1 elapsedTime = float(lap['elapsed_time']) elapsedTimeHours = int(elapsedTime/3600) elapsedTimeMins = int((elapsedTime - (elapsedTimeHours * 3600)) / 60) elapsedTimeSecs = elapsedTime - (elapsedTimeHours * 3600) - (elapsedTimeMins * 60) if elapsedTimeHours > 0: strElapsedTime = "%0.0dh:%0.2dm:%0.2fs" % (elapsedTimeHours, elapsedTimeMins, elapsedTimeSecs) elif elapsedTimeMins > 0: strElapsedTime = "%0.0dm:%0.2fs" % (elapsedTimeMins, elapsedTimeSecs) else: strElapsedTime = "%0.0fs" % (elapsedTimeSecs) #process lat and lon for this lap lapLat = float(lap['end_lat']) lapLon = float(lap['end_lon']) #build laps content string lapsContent+=',\n' lapsContent+='\t\t\t\t\tlap%d: { url : "/waypoint.png", coordinates : [%f,%f], popupInfo: "%s" }' % \ (lapNumber, lapLon, lapLat, \ "<div class='info_content'>End of lap:%d<br>Elapsed time:%s<br>Distance:%0.2f km<br>Calories:%s</div>" % \ (lapNumber, strElapsedTime, float(lap['distance'])/1000, lap['calories']) ) content+=lapsContent except Exception as e: # If something breaks here just skip laps data logging.error('Error formating laps data: ' + str(e)) # Insert start/finish track markers content+=''',\n start : { url : "/start.png", coordinates : %s, popupInfo : "%s" }, finish : { url : "/finish.png", coordinates : %s, popupInfo : "%s" }, url : "file://%s/glade"''' \ % (polyline[0], startinfo, polyline[-1], finishinfo, os.path.abspath(self.data_path)) content+='''};\n function init() { // fool openlayers scripts so it will download images and themes from the web instead of local folder if cached OpenLayers.ImgPath="''' + self.staticURLS['OpenLayers'] + '''img/"; OpenLayers.scriptLocation="''' + self.staticURLS['OpenLayers'] + '''"; OpenLayers._getScriptLocation=function() { return "''' + self.staticURLS['OpenLayers'] + '''";}; // for transforming WGS 1984 to Spherical Mercator Projection pWGS = new OpenLayers.Projection("EPSG:4326"); pMP = new OpenLayers.Projection("EPSG:900913"); map = new OpenLayers.Map ("map", { controls:[ new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Attribution()], maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34), maxResolution: 156543.0399, numZoomLevels: 19, units: 'm', projection: pMP, displayProjection: pWGS } ); // Track painting style var trackStyle = { strokeColor: "#33DDDD", strokeWidth: 3, strokeDashstyle: "solid", strokeOpacity: 0.6, pointRadius: 6, }; //Build track object var track = { "type":"Feature", "id":"OpenLayers.Feature.Vector_259", "properties":{}, "geometry": { "type":"LineString", "coordinates": [''' #Insert track points here content+=",".join(polyline); content+='''] }, "crs": { "type":"OGC", "properties": { "urn":"urn:ogc:def:crs:OGC:1.3:CRS84" } } } //Add open street maps layers layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik"); map.addLayer(layerMapnik); layerTilesAtHome = new OpenLayers.Layer.OSM.Osmarender("Osmarender"); map.addLayer(layerTilesAtHome); //Create vector layer to add the data on to var vector_layer = new OpenLayers.Layer.Vector(); vector_layer.setName('Track'); var geojson_format = new OpenLayers.Format.GeoJSON(); var feature = geojson_format.read(track,"Feature"); // transform from WGS 1984 to Spherical Mercator Projection feature.geometry.transform(pWGS, pMP); feature.geometry.calculateBounds(); var vector=new OpenLayers.Feature.Vector(); vector.geometry = feature.geometry; vector.style=trackStyle; vector_layer.addFeatures(vector); map.addLayer(vector_layer); // Insert start/finish markers layerMarkers = new OpenLayers.Layer.Markers("Markers"); var offset = new OpenLayers.Pixel(-(icons.iconSize.w/2), -icons.iconSize.h); for (var i in icons) { if (icons[i].coordinates) { icons[i].icon = new OpenLayers.Icon(icons.url + icons[i].url,icons.iconSize,offset); icons[i].lonLat = new OpenLayers.LonLat(icons[i].coordinates[0],icons[i].coordinates[1]); icons[i].lonLat.transform(pWGS,pMP); icons[i].marker = new OpenLayers.Marker(icons[i].lonLat,icons[i].icon); icons[i].popup = new OpenLayers.Popup.FramedCloud("Info", icons[i].lonLat, null, icons[i].popupInfo, icons[i].icon, true, null ); icons[i].onClick = function(e) { map.addPopup(this.popup); this.popup.show(); } icons[i].marker.events.register("mousedown", icons[i], function(e) { this.onClick(e)} ) layerMarkers.addMarker(icons[i].marker); } } map.addLayer(layerMarkers); //zoom and center to the track layouts map.zoomToExtent(feature.geometry.getBounds()); } </script> </head> <!-- body.onload is called once the page is loaded (call the 'init' function) --> <body onload="init();"> <!-- define a DIV into which the map will appear. Make it take up the whole window --> <div style="width:100%; height:100%" id="map"></div> </body> </html> ''' file = fileUtils(self.htmlfile,content) file.run() logging.debug("<<")
def selectArea(self,dc=None): # try using local cached versions of JS files for faster rendering self.cacheUrls(); content = ''' <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="../theme/default/style.css" type="text/css" /> <link rel="stylesheet" href="style.css" type="text/css" /> <style type="text/css"> p { width: 512px; } #config { margin-top: 1em; width: 512px; position: relative; height: 8em; } #controls { padding-left: 2em; margin-left: 0; width: 12em; } #controls li { padding-top: 0.5em; list-style: none; } #options { font-size: 1em; top: 0; margin-left: 15em; position: absolute; } /* avoid pink tiles */ .olImageLoadError { background-color: transparent !important; } </style> <!-- Load libraries from remote or local cache --> <script src="''' + self.URLS['OpenLayers.js'] + '''"></script> <script src="''' + self.URLS['OpenStreetMap.js'] + '''"></script> <script type="text/javascript"> var map, polygonControl; function init(){ //"fix" locations OpenLayers.ImgPath="''' + self.staticURLS['OpenLayers'] + '''img/"; OpenLayers.scriptLocation="''' + self.staticURLS['OpenLayers'] + '''"; OpenLayers._getScriptLocation=function() { return "''' + self.staticURLS['OpenLayers'] + '''";}; // for transforming WGS 1984 to Spherical Mercator Projection pWGS = new OpenLayers.Projection("EPSG:4326"); pMP = new OpenLayers.Projection("EPSG:900913"); map = new OpenLayers.Map ("map", { controls:[ new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Attribution(), new OpenLayers.Control.MousePosition()], maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34), maxResolution: 156543.0399, numZoomLevels: 19, units: 'm', projection: pMP, displayProjection: pWGS } ); //Add open street maps layers layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik"); map.addLayer(layerMapnik); layerTilesAtHome = new OpenLayers.Layer.OSM.Osmarender("Osmarender"); map.addLayer(layerTilesAtHome); //Add polygon drawing layer var polygonLayer = new OpenLayers.Layer.Vector("Polygon Layer"); map.addLayer(polygonLayer); polyOptions = {sides: 4, irregular: true}; polygonControl = new OpenLayers.Control.DrawFeature(polygonLayer, OpenLayers.Handler.RegularPolygon, {handlerOptions: polyOptions}); // For desrializings var out_options = { 'internalProjection': map.baseLayer.projection, 'externalProjection': pWGS }; // allow only one feature to be drawn polygonLayer.events.register("beforefeatureadded", polygonLayer, function(f) { polygonLayer.removeAllFeatures(true)}); // Change title after draw polygonLayer.events.register("featureadded", polygonLayer, function(f) { var title=(new OpenLayers.Format.GeoJSON(out_options).write(f.feature,false)); document.title=title; }); //prepaint saved polygon savedPolygon = \'''' + str(self.waypoint) + '''\'; if ((savedPolygon) && (savedPolygon!=='None')) { // deserialize var geojson_format = new OpenLayers.Format.GeoJSON(out_options); var feature = geojson_format.read(savedPolygon); // make sure it's an array if(feature.constructor != Array) feature = [feature]; if (feature && feature.length>0) { var bounds = feature[0].geometry.getBounds(); polygonLayer.addFeatures(feature); map.zoomToExtent(bounds); } } else { map.setCenter(new OpenLayers.LonLat(0, 0), 3); } map.addControl(polygonControl); document.getElementById('noneToggle').checked = true; } function setOptions(options) { polygonControl.handler.setOptions(options); } function setSize(fraction) { var radius = fraction * map.getExtent().getHeight(); polygonControl.handler.setOptions({radius: radius, angle: 0}); } </script> </head> <body onload="init()"> <input type="radio" name="type" value="none" id="noneToggle" onclick="polygonControl.deactivate()" checked="checked" /> <label for="noneToggle">Navigate</label> <input type="radio" name="type" value="polygon" id="polygonToggle" onclick="polygonControl.activate()" /> <label for="polygonToggle">Draw polygon</label> <div id="map" class="smallmap"></div> </body> </html>''' file = fileUtils(self.htmlfile,content) file.run() return self.htmlfile