I am trying to integrate cloudmade routing with leaflet as follows:
1. Click a point on the map to set a starting point for a rout and directions
2. Click a second point on the map to set an ending point for a rout and directions
3. display the rout as a polyline and output the directions to a panel.
All examples, posts, etc..., show this being done with fixed latlng values and no click events. This has easily been accomplished. However, How can I accomplish what would be a more realistic user interaction, i.e., steps 1-3 above?
I have tried to set up a switch but it only goes to the first case (route start) and does not advance to the second case (route end) on the second click.
I had been able to get this to work on openlayers using a script that I found from a couple of years ago, but I do not want to use openlayers. I tried to modify the script for leaflet but have not been able to get any farther than step 1 above.
Here is the code I am working with. Please disregard how dirty it is, but it has gone through a zillion iterations of values, all to no avail. Any help will be MOST appreciated!
Thank you in advance!
var map, latlng, fromMarker, toMarker;
map = L.map('map').setView([44.85721, -92.62796], 14);
L.tileLayer('http://{s}.
tile.cloudmade.com/api-key/80880/256/{z}/{x}/{y}.png', {
attribution: 'Map data © <a href="
http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="
http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery ?<a href="
http://cloudmade.com">CloudMade</a>',
maxZoom: 18,
}).addTo(map);
function addScript(url) {
var script = document.createElement('script');
script.type="text/javascript";
script.src=url;
document.getElementsByTagName('head') [0].appendChild(script);
}
function getRoute (response) {
var point, route, points = [];
for (var i = 0; i < response.route_geometry.length; i++) {
var point = new L.LatLng(response.route_geometry[i][0] , response.route_geometry[i][1]);
points.push(point);
route= new L.Polyline(points, {
weight: 3,
opacity: 0.5,
smoothFactor: 1
}).addTo(map);
route.bringToFront();
}}
function onMapClick(e) {
var Lat = (e.latlng.lat);
var Lng = (e.latlng.lng);
var i = 1;
switch (i) {
case 1: from = map.latLngToContainerPoint(e);
fromMarker ? e.remove(fromMarker) : null;
toMarker ? e.remove(toMarker) : null;
fromMarker = new L.Marker(new L.LatLng(Lat,Lng),{title:'route start'}).addTo(map);
break;
case 2: to = map.latLngToContainerPoint(e);
toMarker = new L.marker(new L.LatLng(Lat,Lng),{title:'route end'}).addTo(map);
break;
i +=1
if (i == 3) {
route.remove();
addScript('
http://routes.cloudmade.com/api-key/api/0.3/' + fromMarker.getLatLng().lat + ',' + fromMarker.getLatLng().lng + ',' + toMarker.getLatLng().lat + ',' + toMarker.getLatLng().lng + '/car.js?callback=getRoute');
i = 1
}
}}
map.on('click', onMapClick);