Hello Daniweb,
I'm attempting to build an online service, aimed at mobile devices that have GPS or GPS like capabilities. The service would take a users location, and show them locations nearby of interest along with some information, such as a historic landmark and some facts or a restaurant with reviews from other users of the service.
I was planning on using HTML5's Geolocation feature alongside OpenStreetMap tile data. Everything is working fine up until the point where I try and translate a latitude and longitude to a pixel so that I can draw a little marker onto the map.
This is what I have so far:
window.onload = function() {
/* Check for Location Service Support */
if(navigator.geolocation) {
/* Begin Geolocating */
var watchID = navigator.geolocation.getCurrentPosition(fetchGeoLocation, geoLocationError, {
enableHighAccuracy: true, timeout: 27000, maximumAge: 30000
});
}
else {
alert("Your Browser Doesn't Support GeoLocational Services");
}
/* Error Callback */
function geoLocationError(error) {
alert(error);
}
/* fetchGeoLocation, Map Rendering and Marker Placement */
var lat = position.coords.latitude; // Latitude (Y Axis)
var lon = position.coords.longitude; // Longitude (X Axis)
var acc = position.coords.accuracy; // Accuracy of Reading
var zoom = 15; // Map Detail (Zoom Level)
/* Folder/Tile Algorithm Modified from http://wiki.openstreetmap.org/wiki/Tilenames#ECMAScript_.28JavaScript.2FActionScript.2C_etc..29 */
var folder = Math.floor((lon+180)/360*Math.pow(2,zoom)); // Folder (Longitude)
var tile = Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom)); // Tile (Latitude)
/* Prepare Canvas for Write */
var canvas = document.getElementById('mapArea');
var context = canvas.getContext('2d');
/* Load Images */
var mapTile = new Image(); // Tile for Longitude and Latitude Range
mapTile.onload = function() {
context.drawImage(mapTile, 0, 0, 256, 256); // Draw Tile onto Canvas
}
mapTile.src = "/Assets/Tiles/" + zoom + "/" + folder + "/" + tile + ".png";
}
Sorry about the formatting, I use a fair amount of indentation to line up my comments which works fine on my screen however in Daniweb, it is squeezed because of the post dimensions.
The code above shall take the coordinates of the person fine, and it shall display the relevant map piece which uses the standard OSM Naming Schema. The problem is, how do I take the latitude and longitude and turn it into a pixel on the 256px square so that I can add a marker. I've read about Mercator Projection, and I've found a lot of formulas but to be honest... it is all going over my head.
I've spent the past two days trying to work this out but with no success, so I am hoping one of you shall be able to help!
Thanks in Advance!