_routeDone: function(response, inputWaypoints, callback, context) {
        var coordinates,
            alts,
            actualWaypoints,
            i;
        context = context || callback;
        if (response.trip.status !== 0) {
          callback.call(context, {
            status: response.status,
            message: response.status_message
          });
          return;
        }

       //if valhalla changes to array of objects
        var insts = [];
        var coordinates = [];
        var shapeIndex =  0;
        for(var i = 0; i<response.trip.legs.length;  i++){
          var coord = polyline.decode(response.trip.legs[i].shape, 6);

          for(var k = 0; k < coord.length; k++){
            coordinates.push(coord[k]);
          }

          for(var j =0; j < response.trip.legs[i].maneuvers.length; j++){
            var res = response.trip.legs[i].maneuvers[j];
            res.distance = response.trip.legs[i].maneuvers[j]["length"];
            res.index = shapeIndex + response.trip.legs[i].maneuvers[j]["begin_shape_index"];
            res.maneuvernum = j+1;
            insts.push(res);
          }

          shapeIndex += response.trip.legs[i].maneuvers[response.trip.legs[i].maneuvers.length-1]["begin_shape_index"];
        }
        actualWaypoints = this._toWaypoints(inputWaypoints, response.trip.locations);


        alts = [{
          ////gotta change
          name: this._trimLocationKey(inputWaypoints[0].latLng) + " </div><div class='dest'> " + this._trimLocationKey(inputWaypoints[1].latLng) ,
          unit: response.trip.units,
          transitmode: this._transitmode,
          rrshape: this._rrshape,
          graphdata: this.graphdata,
          graphoptions: this.graphoptions,
          coordinates: coordinates,
          instructions: insts,//response.route_instructions ? this._convertInstructions(response.route_instructions) : [],
          summary: response.trip.summary ? this._convertSummary(response.trip.summary) : [],
          inputWaypoints: inputWaypoints,
          waypoints: actualWaypoints,
          waypointIndices: this._clampIndices([0,response.trip.legs[0].maneuvers.length], coordinates)
        }];

        // only versions <4.5.0 will support this flag
          if (response.hint_data) {
            this._saveHintData(response.hint_data, inputWaypoints);
          }
        callback.call(context, null, alts);
      },
		    		leg.steps.forEach(function(step) { // in each step of the route...
		    			array = polyline.decode(step.polyline.points);
		    			lastPair = []; // keep track of the last point we saw so we can decide if we have to recheck the next one
		    			lastAlerts = []; // if the point was close enough, the alerts for this step are the same as for the last step
		    			array.forEach(function (latLongPair){ 
						    thisLat = latLongPair[0];
		    				thisLong = latLongPair[1];
			    			if (lastPair.length==0 || (Math.abs(lastPair[0]-thisLat) > displacement && Math.abs(lastPair[1]-thisLong) > displacement)) {
		    					numQueries += 1;
		    					asyncTasks.push(function(callback2) {
		    						module.context.locations.find({
			    						'latitude':{$gte: thisLat - queryRadius, $lte: thisLat + queryRadius},
			    						'longitude':{$gte: thisLong - queryRadius, $lte: thisLong + queryRadius}
				    				}, {"limit":100}, function(err, docs) {
				    					if (err) {
				    						console.log(err);
				    						callback2(); // tell async the task is done
				    					}
				    					step.alerts = docs;
				    					lastAlerts = docs; // store these for next time
				    					callback2(); // tell async the task is done
								    }); // end find
			    				}); // end of push to asyncTasks
		    				} else {
		    					step.alerts = lastAlerts; // don't bother checking
		    				}
		    				lastPair = latLongPair; // update
						});  
		    		});
Example #3
0
  osrm.trip({coordinates:query}, function (err, result) {
    if (result != undefined && result.trips != undefined) {
      var i;
      for (i = 0; i < currRoute.length; ++i) {
        route.removeLayer(currRoute[i]);
      }
      currRoute = [];
      console.log(result);
      var t;
      for (t = 0; t < result.trips.length; t++) {
        console.log("trips.length " + i);
        if (result.trips[t].route_geometry != undefined) {
          var roundtrip = polyline.decode(result.trips[t].route_geometry, 6);

          var latlng;
          var lineLatLng = [];
          for (latlng = 0; latlng < roundtrip.length; latlng++) {
            var newLatLng = L.latLng(roundtrip[latlng][0], roundtrip[latlng][1]);
            lineLatLng.push(newLatLng);
          }
          currRoute.push(L.polyline(lineLatLng));

          var p;
          for (p = 0; p < result.trips[t].permutation.length; p++){
            markerArray[result.trips[t].permutation[p]].bindPopup('Stop ' + p);
          }
        }
      }
      for (i = 0; i < currRoute.length; ++i) {
        route.addLayer(currRoute[i]);
      }
    }
  });
Example #4
0
module.exports.decode = function(buf) {
    var parts = buf.split('|');
    if (parts.length % 2 !== 0) return null;
    var fs = {
        type: 'FeatureCollection',
        features: []
    };
    for (var i = 0; i < parts.length; i += 2) {
        var geom = polyline.decode(parts[i]);
        var props = parseProps(parts[i + 1]);
        var geometry;
        if (geom.length === 1) {
            geometry = {
                type: 'Point',
                coordinates: geom[0]
            };
        } else {
            geometry = {
                type: 'LineString',
                coordinates: geom
            };
        }
        fs.features.push({
            type: 'Feature',
            geometry: geometry,
            properties: props
        });
    }
    return fs;
};
 subtraces.forEach(function (t) {
   var style = this.options.style;
   if (t.confidence !== undefined)
   {
     style.color = this._gradient(t.confidence);
   }
   var line = L.polyline(polyline.decode(t.geometry, 6)/*t.matched_points*/, style);
   this._group.addLayer(line);
 }.bind(this));
Example #6
0
function getFullPath(route) {
  let fullPath = [];
  for(const leg of route.legs) {
    for(const step of leg.steps) {
      fullPath = fullPath.concat(polyline.decode(step.polyline.points));
    }
  }
  return fullPath;
}
		_decodePolyline: function(routeGeometry) {
			var cs = polyline.decode(routeGeometry, this.options.polylinePrecision),
				result = new Array(cs.length),
				i;
			for (i = cs.length - 1; i >= 0; i--) {
				result[i] = L.latLng(cs[i]);
			}

			return result;
		},
Example #8
0
		_decodePolyline: function(geometry) {
			var coords = polyline.decode(geometry, 5),
				latlngs = new Array(coords.length),
				i;
			for (i = 0; i < coords.length; i++) {
				latlngs[i] = new L.LatLng(coords[i][0], coords[i][1]);
			}

			return latlngs;
		},
Example #9
0
            .then(json => {
                var decoded = Polyline.decode(json.route_geometry);
                console.log("OSRM received, path updated.");

                // TODO: find out why the hell / 10 ?
                dispatch(setPolyLine(
                    decoded.map(point => {
                        return {lat: point[0] / 10, lon: point[1] / 10}
                    })
                ));
            });
Example #10
0
        allData.routes[0].legs[0].steps.forEach(function (r) {
          coordindates = polyline.decode(r.polyline.points);

          //SWAP COORDINATES AND ADJUST BASED ON N,S,E,W!
          coordindates.map(function (coordinate) {
            var swap = coordinate[0];
            coordinate[0] = coordinate[1] + bumpIt[data[pointNr].Side].stepX;
            coordinate[1] = swap + bumpIt[data[pointNr].Side].stepY;
          });

        });
Example #11
0
function polylineParse(txt, options, layer) {
    layer = layer || L.geoJson();
    options = options || {};
    var coords = polyline.decode(txt, options.precision);
    var geojson = { type: 'LineString', coordinates: [] };
    for (var i = 0; i < coords.length; i++) {
        // polyline returns coords in lat, lng order, so flip for geojson
        geojson.coordinates[i] = [coords[i][1], coords[i][0]];
    }
    addData(layer, geojson);
    return layer;
}
		_decodePolyline : function ( routeGeometry ) {
			
			var	polyline = require('polyline');
	
			var coordinates = polyline.decode ( routeGeometry, this.options.polylinePrecision );
			var result = new Array ( coordinates.length );
			
			for ( var coordCounter = coordinates.length - 1; coordCounter >= 0; coordCounter -- ) {
				result [ coordCounter ] = L.latLng ( coordinates [ coordCounter ] );
			}

			return result;
		},
		_decodePolyline: function ( routeGeometry ) {

		var	polyline = require ( 'polyline' );
			
			var coordinates = polyline.decode ( routeGeometry, 5 );
			var result = new Array ( coordinates.length );

			for ( var coordCounter = 0; coordCounter < coordinates.length; coordCounter ++ ) {
				result [ coordCounter ] = L.latLng ( coordinates [ coordCounter ][ 0 ], coordinates [ coordCounter ][ 1 ]);
			}

			return result;
		},
		createRoutes : function ( response, inputWaypoints, routeOptions ) {

			var insts = [ ];
			var coordinates = [ ];
			var shapeIndex =  0;

			for ( var legsCounter = 0; legsCounter < response.trip.legs.length; legsCounter++ ) {
				var coord = polyline.decode ( response.trip.legs [ legsCounter ].shape, 6 );

				for ( var coordCounter = 0; coordCounter < coord.length; coordCounter++ ) {
					coordinates.push ( L.latLng ( coord [ coordCounter ][ 0 ], coord [ coordCounter ][ 1 ] ) );
				}

				for ( var maneuversCounter = 0; maneuversCounter < response.trip.legs [ legsCounter ].maneuvers.length; maneuversCounter++ ){
					var res = response.trip.legs [ legsCounter ].maneuvers [ maneuversCounter ];
					res.distance = response.trip.legs [ legsCounter ].maneuvers [ maneuversCounter ].length;
					res.index = shapeIndex + response.trip.legs [ legsCounter ].maneuvers [ maneuversCounter ].begin_shape_index;
					insts.push ( res );
				}

				if ( routeOptions.costing === 'multimodal' ) {
					insts = this._unifyTransitManeuver ( insts );
				}

				shapeIndex += response.trip.legs [ legsCounter ].maneuvers [ response.trip.legs [ legsCounter ].maneuvers.length-1 ].begin_shape_index;
			}

			var actualWaypoints = this._toWaypoints ( inputWaypoints, response.trip.locations );

			var subRoutes;
			if ( routeOptions.costing == 'multimodal' ) {
				subRoutes = this._getSubRoutes ( response.trip.legs );
			}

			var alts = [
				{
					name : '',
					unit : response.trip.units,
					costing : routeOptions.costing,
					coordinates : coordinates,
					subRoutes : subRoutes,
					instructions : insts,//response.route_instructions ? this._convertInstructions(response.route_instructions) : [],
					summary : response.trip.summary ? this._convertSummary ( response.trip.summary ) : [ ],
					inputWaypoints: inputWaypoints,
					waypoints: actualWaypoints,
					waypointIndices: this._clampIndices ( [ 0, response.trip.legs [ 0 ].maneuvers.length ], coordinates )
				}
			];

			return alts;
		},
Example #15
0
 matchedFeature.features = matchedFeature.features.map(function (feature) {
     var decodedFeature = {
         "type": "Feature",
         "properties": feature.properties,
         "geometry": {
             "type": "LineString",
             // Invert latLon to lonLat because polyline is left brained
             "coordinates": polyline.decode(feature.geometry, 6).map(function (coords) {
                 return [coords[1], coords[0]];
             })
         }
     };
     return decodedFeature;
 });
    _getSubRoutes: function(legs) {

      var subRoute = [];

      for (var i = 0; i < legs.length; i++) {

        var coords = polyline.decode(legs[i].shape, 6);

        var lastTravelType;
        var transitIndices = [];
        for(var j = 0; j < legs[i].maneuvers.length; j++){

          var res = legs[i].maneuvers[j];
          var travelType = res.travel_type;

          if(travelType !== lastTravelType || res.type === 31 /*this is for transfer*/) {
            //transit_info only exists in the transit maneuvers
            //loop thru maneuvers and populate indices array with begin shape index
            //also populate subRoute array to contain the travel type & color associated with the transit polyline sub-section
            //otherwise just populate with travel type and use fallback style
            if(res.begin_shape_index > 0) transitIndices.push(res.begin_shape_index);
            if(res.transit_info) subRoute.push({ travel_type: travelType, styles: this._getPolylineColor(res.transit_info.color) })
            else subRoute.push({travel_type: travelType})
          }

          lastTravelType = travelType;
        }

        //add coords length to indices array
        transitIndices.push(coords.length);

        //logic to create the subsets of the polyline by indexing into the shape
        var index_marker = 0;
        for(var index = 0; index < transitIndices.length; index++) {
          var subRouteArr = [];
          var overwrapping = 0;
          //if index != the last indice, we want to overwrap (or add 1) so that routes connect
          if(index !== transitIndices.length-1) overwrapping = 1;
          for (var ti = index_marker; ti < transitIndices[index] + overwrapping; ti++){
            subRouteArr.push(coords[ti]);
          }

          var temp_array = subRouteArr;
          index_marker = transitIndices[index];
          subRoute[index].coordinates = temp_array;
        }
      }
      return subRoute;
    },
Example #17
0
/**
 * Convert GraphHopper routing JSON response to polyline.
 */
function handleGraphHopperRouting (path: Path, individualLegs: boolean = false): any {
  const {instructions, points} = path
  // Decode polyline and reverse coordinates.
  const decodedPolyline = decodePolyline(points).map(c => ([c[1], c[0]]))
  if (individualLegs) {
    // Reconstruct individual legs from the instructions. NOTE: we do not simply
    // use the waypoints found in the response because for lines that share
    // street segments, slicing on these points results in unpredictable splits.
    // Slicing the line along distances is much more reliable.
    const segments = []
    const waypointDistances = [0]
    let distance = 0
    // Iterate over the instructions, accumulating distance and storing the
    // distance at each waypoint encountered. Distances are used to slice the
    // line geometry if individual legs are needed. NOTE: Waypoint === routing
    // point provided in the request.
    instructions.forEach(instruction => {
      if (instruction.text.match(/Waypoint (\d+)/)) {
        // Add distance value to list
        waypointDistances.push(distance)
      } else {
        distance += instruction.distance
      }
    })
    // Add last distance measure.
    // FIXME: Should this just be the length of the entire line?
    // console.log(waypointDistances, json.paths[0].distance)
    waypointDistances.push(distance)
    const decodedLineString = lineString(decodedPolyline)
    if (waypointDistances.length > 2) {
      for (var i = 1; i < waypointDistances.length; i++) {
        const slicedSegment = lineSliceAlong(
          decodedLineString,
          waypointDistances[i - 1] / 1000,
          waypointDistances[i] / 1000
        )
        segments.push(slicedSegment.geometry.coordinates)
      }
      // console.log('individual legs', segments)
      return segments
    } else {
      // FIXME does this work for two input points?
      return [decodedPolyline]
    }
  } else {
    return decodedPolyline
  }
}
 onRouteReceived: function (toid, response) { // TODO: Refactor
   if (toid in this.routingFeatures) {
     if (response.status === "OK" && response.routes && response.routes.length) {
       const googleRoute = response.routes[0];
       const googlePs = googlePolyline.decode(googleRoute.overview_polyline.points);
       const ps = [];
       for (let i = 0; i < googlePs.length; i++) {
         const latLon = googlePs[i];
         ps.push(nnng.to(latLon[0], latLon[1]));
       }
       const route = this.routingFeatures[toid].route;
       route.importedPoints = ps;
       const whiteList = this.findCloseRoadNodesToPolyline(10, ps);
       let firstNode, lastNode;
       let firstDistance = Infinity;
       let lastDistance = Infinity;
       for (let i = 0; i < whiteList.length; i++) {
         const current = whiteList[i];
         const startDistance = this.geometry.getDistanceBetweenRoadNodes(route.startNode, current);
         const endDistance = this.geometry.getDistanceBetweenRoadNodes(current, route.endNode);
         if (startDistance < firstDistance) {
           firstDistance = startDistance;
           firstNode = current;
         }
         if (endDistance < lastDistance) {
           lastDistance = endDistance;
           lastNode = current;
         }
       }
       if (firstNode && lastNode) {
         const importedRoute = this.geometry.findShortestRouteBetweenRoadNodes(firstNode, lastNode, null, whiteList);
         if (importedRoute && importedRoute.roadLinks.length) {
           route.roadLinks = importedRoute.roadLinks;
         } else {
           console.log("Could not determine importedRoute", firstNode, lastNode, importedRoute); // TODO
         }
       } else {
         console.log("Could not determine firstNode or lastNode", firstNode, lastNode, whiteList); // TODO
       }
       this.renderRoutingFeatures();
       this.sendRoutes();
     } else {
       console.log("Google failed:", toid, response); // TODO
     }
   } else {
     console.log("Google was late:", toid, response); // TODO
   }
 },
Example #19
0
		.then(function(result){
			// console.log(JSON.stringify(result));
			if(result.status == 'OK'){
				var encodePolyline = result.routes[0].overview_polyline.points;
				// console.log('Encode: ', encodePolyline);
				var polylines = polyline.decode(result.routes[0].overview_polyline.points);
				// console.log('Decode: ', polylines);
				var roads = [];
				for(var i=0;i<polylines.length;i++){
					var point = {
						latitude: polylines[i][0],
						longitude: polylines[i][1]
					}
					roads.push(point);
				}
				// console.log('Send to client: ', roads);
				socket.emit('find_way', {coordinates: roads});
			}
		})
 .reduce(function(total, step){
     return total.concat(polyline.decode(step.polyline.points))
 }, [])
Example #21
0
var polyline = require('polyline');

// returns an array of lat, lon pairs
console.log(polyline.decode('_p~iF~ps|U_ulLnnqC_mqNvxq`@'));

// returns a string-encoded polyline
console.log(polyline.encode([[38.5, -120.2], [40.7, -120.95], [43.252, -126.453]]));
!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){function corslite(url,callback,cors){function isSuccessful(status){return status>=200&&300>status||304===status}function loaded(){void 0===x.status||isSuccessful(x.status)?callback.call(x,null,x):callback.call(x,x,null)}var sent=!1;if("undefined"==typeof window.XMLHttpRequest)return callback(Error("Browser not supported"));if("undefined"==typeof cors){var m=url.match(/^\s*https?:\/\/[^\/]*/);cors=m&&m[0]!==location.protocol+"//"+location.domain+(location.port?":"+location.port:"")}var x=new window.XMLHttpRequest;if(cors&&!("withCredentials"in x)){x=new window.XDomainRequest;var original=callback;callback=function(){if(sent)original.apply(this,arguments);else{var that=this,args=arguments;setTimeout(function(){original.apply(that,args)},0)}}}return"onload"in x?x.onload=loaded:x.onreadystatechange=function(){4===x.readyState&&loaded()},x.onerror=function(evt){callback.call(this,evt||!0,null),callback=function(){}},x.onprogress=function(){},x.ontimeout=function(evt){callback.call(this,evt,null),callback=function(){}},x.onabort=function(evt){callback.call(this,evt,null),callback=function(){}},x.open("GET",url,!0),x.send(null),sent=!0,x}"undefined"!=typeof module&&(module.exports=corslite)},{}],2:[function(require,module,exports){function encode(coordinate,factor){coordinate=Math.round(coordinate*factor),coordinate<<=1,0>coordinate&&(coordinate=~coordinate);for(var output="";coordinate>=32;)output+=String.fromCharCode((32|31&coordinate)+63),coordinate>>=5;return output+=String.fromCharCode(coordinate+63)}var polyline={};polyline.decode=function(str,precision){for(var latitude_change,longitude_change,index=0,lat=0,lng=0,coordinates=[],shift=0,result=0,byte=null,factor=Math.pow(10,precision||5);index<str.length;){byte=null,shift=0,result=0;do byte=str.charCodeAt(index++)-63,result|=(31&byte)<<shift,shift+=5;while(byte>=32);latitude_change=1&result?~(result>>1):result>>1,shift=result=0;do byte=str.charCodeAt(index++)-63,result|=(31&byte)<<shift,shift+=5;while(byte>=32);longitude_change=1&result?~(result>>1):result>>1,lat+=latitude_change,lng+=longitude_change,coordinates.push([lat/factor,lng/factor])}return coordinates},polyline.encode=function(coordinates,precision){if(!coordinates.length)return"";for(var factor=Math.pow(10,precision||5),output=encode(coordinates[0][0],factor)+encode(coordinates[0][1],factor),i=1;i<coordinates.length;i++){var a=coordinates[i],b=coordinates[i-1];output+=encode(a[0]-b[0],factor),output+=encode(a[1]-b[1],factor)}return output},void 0!==typeof module&&(module.exports=polyline)},{}],3:[function(require,module,exports){(function(global){!function(){"use strict";var t="undefined"!=typeof window?window.L:"undefined"!=typeof global?global.L:null,e=require("corslite"),n=require("polyline");t.Routing=t.Routing||{},t.Routing.Mapzen=t.Class.extend({options:{timeout:3e4},initialize:function(e,n){t.Util.setOptions(this,n),this._accessToken=e,this._hints={locations:{}}},route:function(n,i,o,s){var a,r,l,u,p=!1,c=[],h={};for(h=this.options||{},a=this.buildRouteUrl(n,h),r=setTimeout(function(){p=!0,i.call(o||i,{status:-1,message:"Time out."})},this.options.timeout),u=0;u<n.length;u++)l=n[u],c.push({latLng:l.latLng,name:l.name||"",options:l.options||{}});return e(a,t.bind(function(t,e){var n;clearTimeout(r),p||(t?(console.log("Error : "+t.response),i.call(o||i,{status:t.status,message:t.response})):(n=JSON.parse(e.responseText),this._routeDone(n,c,h,i,o)))},this),!0),this},_routeDone:function(t,e,i,o,s){var a,r,l,u;if(s=s||o,0!==t.trip.status)return void o.call(s,{status:t.status,message:t.status_message});for(var p=[],a=[],c=0,u=0;u<t.trip.legs.length;u++){for(var h=n.decode(t.trip.legs[u].shape,6),g=0;g<h.length;g++)a.push(h[g]);for(var _=0;_<t.trip.legs[u].maneuvers.length;_++){var m=t.trip.legs[u].maneuvers[_];m.distance=t.trip.legs[u].maneuvers[_].length,m.index=c+t.trip.legs[u].maneuvers[_].begin_shape_index,p.push(m)}"multimodal"===i.costing&&(p=this._unifyTransitManeuver(p)),c+=t.trip.legs[u].maneuvers[t.trip.legs[u].maneuvers.length-1].begin_shape_index}l=this._toWaypoints(e,t.trip.locations);var v;"multimodal"==i.costing&&(v=this._getSubRoutes(t.trip.legs)),r=[{name:this._trimLocationKey(e[0].latLng)+" , "+this._trimLocationKey(e[1].latLng),unit:t.trip.units,costing:i.costing,coordinates:a,subRoutes:v,instructions:p,summary:t.trip.summary?this._convertSummary(t.trip.summary):[],inputWaypoints:e,waypoints:l,waypointIndices:this._clampIndices([0,t.trip.legs[0].maneuvers.length],a)}],t.hint_data&&this._saveHintData(t.hint_data,e),o.call(s,null,r)},_unifyTransitManeuver:function(t){for(var e,n=t,i=0;i<n.length;i++)if(30==n[i].type){e=n[i].travel_type;break}for(var o=0;o<n.length;o++)n[o].type>29&&(n[o].edited_travel_type=e);return n},_getSubRoutes:function(t){for(var e=[],i=0;i<t.length;i++){for(var o,s=n.decode(t[i].shape,6),a=[],r=0;r<t[i].maneuvers.length;r++){var l=t[i].maneuvers[r],u=l.travel_type;u===o&&31!==l.type||(l.begin_shape_index>0&&a.push(l.begin_shape_index),l.transit_info?e.push({travel_type:u,styles:this._getPolylineColor(l.transit_info.color)}):e.push({travel_type:u})),o=u}a.push(s.length);for(var p=0,c=0;c<a.length;c++){var h=[],g=0;c!==a.length-1&&(g=1);for(var _=p;_<a[c]+g;_++)h.push(s[_]);var m=h;p=a[c],e[c].coordinates=m}}return e},_getPolylineColor:function(t){var e=t>>16&255,n=t>>8&255,i=t>>0&255,o=.299*e+.587*n+.114*i,s=o>187,a=16777216|16777215&t,r=a.toString(16).substring(1,7),l=[s?{color:"#000",opacity:.4,weight:10}:{color:"#fff",opacity:.8,weight:10},{color:"#"+r.toUpperCase(),opacity:1,weight:6}];return l},_saveHintData:function(t,e){var n;this._hints={checksum:t.checksum,locations:{}};for(var i=t.locations.length-1;i>=0;i--)n=e[i].latLng,this._hints.locations[this._locationKey(n)]=t.locations[i]},_toWaypoints:function(e,n){var i,o=[];for(i=0;i<n.length;i++)o.push(t.Routing.waypoint(t.latLng([n[i].lat,n[i].lon]),"name",{}));return o},buildRouteUrl:function(t,e){for(var n,i="https://valhalla.mapzen.com",o=[],s=e.costing,a=e.costing_options,r=e.directions_options,l=e.date_time,u=0;u<t.length;u++){var p;n=this._locationKey(t[u].latLng).split(","),p=0===u||u===t.length-1?{lat:parseFloat(n[0]),lon:parseFloat(n[1]),type:"break"}:{lat:parseFloat(n[0]),lon:parseFloat(n[1]),type:"through"},o.push(p)}var c=JSON.stringify({locations:o,costing:s,costing_options:a,directions_options:r,date_time:l});return i+"/route?json="+c+"&api_key="+this._accessToken},_locationKey:function(t){return t.lat+","+t.lng},_trimLocationKey:function(t){var e=(t.lat,t.lng,Math.floor(1e3*t.lat)/1e3),n=Math.floor(1e3*t.lng)/1e3;return e+" , "+n},_convertSummary:function(t){return{totalDistance:t.length,totalTime:t.time}},_convertInstructions:function(t){var e,n,i,o,s=[];for(e=0;e<t.length;e++)n=t[e],i=this._drivingDirectionType(n[0]),o=n[0].split("-"),i&&s.push({type:i,distance:n[2],time:n[4],road:n[1],direction:n[6],exit:o.length>1?o[1]:void 0,index:n[3]});return s},_clampIndices:function(t,e){var n,i=e.length-1;for(n=0;n<t.length;n++)t[n]=Math.min(i,Math.max(t[n],0))}}),t.Routing.mapzen=function(e,n){return new t.Routing.Mapzen(e,n)},module.exports=t.Routing.Mapzen}()}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{corslite:1,polyline:2}],4:[function(require,module,exports){(function(global){!function(){"use strict";var t="undefined"!=typeof window?window.L:"undefined"!=typeof global?global.L:null;t.Routing=t.Routing||{},t.Routing.MapzenFormatter=t.Class.extend({options:{units:"metric",unitNames:{meters:"m",kilometers:"km",yards:"yd",miles:"mi",hours:"h",minutes:"mín",seconds:"s"},language:"en",roundingSensitivity:1,distanceTemplate:"{value} {unit}"},initialize:function(e){t.setOptions(this,e)},formatDistance:function(e){var n,r,i=this.options.unitNames;return"imperial"===this.options.units?(e=1e3*e,e/=1.609344,r=e>=1e3?{value:this._round(e)/1e3,unit:i.miles}:{value:this._round(e/1.76),unit:i.yards}):(n=e,r={value:n>=1?n:1e3*n,unit:n>=1?i.kilometers:i.meters}),t.Util.template(this.options.distanceTemplate,r)},_round:function(t){var e=Math.pow(10,(Math.floor(t/this.options.roundingSensitivity)+"").length-1),n=Math.floor(t/e),r=n>5?e:e/2;return Math.round(t/r)*r},formatTime:function(t){return t>86400?Math.round(t/3600)+" h":t>3600?Math.floor(t/3600)+" h "+Math.round(t%3600/60)+" min":t>300?Math.round(t/60)+" min":t>60?Math.floor(t/60)+" min"+(t%60!==0?" "+t%60+" s":""):t+" s"},formatInstruction:function(t,e){return t.instruction},getIconName:function(t,e){switch(t.type){case 0:return"kNone";case 1:return"kStart";case 2:return"kStartRight";case 3:return"kStartLeft";case 4:return"kDestination";case 5:return"kDestinationRight";case 6:return"kDestinationLeft";case 7:return"kBecomes";case 8:return"kContinue";case 9:return"kSlightRight";case 10:return"kRight";case 11:return"kSharpRight";case 12:return"kUturnRight";case 13:return"kUturnLeft";case 14:return"kSharpLeft";case 15:return"kLeft";case 16:return"kSlightLeft";case 17:return"kRampStraight";case 18:return"kRampRight";case 19:return"kRampLeft";case 20:return"kExitRight";case 21:return"kExitLeft";case 22:return"kStayStraight";case 23:return"kStayRight";case 24:return"kStayLeft";case 25:return"kMerge";case 26:return"kRoundaboutEnter";case 27:return"kRoundaboutExit";case 28:return"kFerryEnter";case 29:return"kFerryExit";case 30:case 31:case 32:case 33:case 34:case 35:case 36:return t.edited_travel_type?"kTransit"+this._getCapitalizedName(t.edited_travel_type):"kTransit"}},_getInstructionTemplate:function(t,e){return t.instruction+" "+t.length},_getCapitalizedName:function(t){return t.charAt(0).toUpperCase()+t.slice(1)}}),t.Routing.mapzenFormatter=function(){return new t.Routing.MapzenFormatter},module.exports=t.Routing}()}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],5:[function(require,module,exports){(function(global){!function(){"use strict";var t="undefined"!=typeof window?window.L:"undefined"!=typeof global?global.L:null;t.Routing=t.Routing||{},t.Routing.MapzenLine=t.LayerGroup.extend({includes:t.Mixin.Events,options:{styles:[{color:"black",opacity:.15,weight:9},{color:"white",opacity:.8,weight:6},{color:"red",opacity:1,weight:2}],missingRouteStyles:[{color:"black",opacity:.15,weight:7},{color:"white",opacity:.6,weight:4},{color:"gray",opacity:.8,weight:2,dashArray:"7,12"}],addWaypoints:!0,extendToWaypoints:!0,missingRouteTolerance:10},initialize:function(i,e){if(t.setOptions(this,e),t.LayerGroup.prototype.initialize.call(this,e),this._route=i,this.options.extendToWaypoints&&this._extendToWaypoints(),i.subRoutes)for(var o=0;o<i.subRoutes.length;o++)i.subRoutes[o].styles||(i.subRoutes[o].styles=this.options.styles),this._addSegment(i.subRoutes[o].coordinates,i.subRoutes[o].styles,this.options.addWaypoints);else this._addSegment(i.coordinates,this.options.styles,this.options.addWaypoints)},addTo:function(t){return console.log("this line!"),t.addLayer(this),this},getBounds:function(){return t.latLngBounds(this._route.coordinates)},_findWaypointIndices:function(){var t,i=this._route.inputWaypoints,e=[];for(t=0;t<i.length;t++)e.push(this._findClosestRoutePoint(i[t].latLng));return e},_findClosestRoutePoint:function(t){var i,e,o,n=Number.MAX_VALUE;for(e=this._route.coordinates.length-1;e>=0;e--)o=t.distanceTo(this._route.coordinates[e]),n>o&&(i=e,n=o);return i},_extendToWaypoints:function(){var i,e,o,n=this._route.inputWaypoints,s=this._getWaypointIndices();for(i=0;i<n.length;i++)e=n[i].latLng,o=t.latLng(this._route.coordinates[s[i]]),e.distanceTo(o)>this.options.missingRouteTolerance&&this._addSegment([e,o],this.options.missingRouteStyles)},_addSegment:function(i,e,o){var n,s;for(n=0;n<e.length;n++)s=t.polyline(i,e[n]),this.addLayer(s),o&&s.on("mousedown",this._onLineTouched,this)},_findNearestWpBefore:function(t){for(var i=this._getWaypointIndices(),e=i.length-1;e>=0&&i[e]>t;)e--;return e},_onLineTouched:function(t){var i=this._findNearestWpBefore(this._findClosestRoutePoint(t.latlng));this.fire("linetouched",{afterIndex:i,latlng:t.latlng})},_getWaypointIndices:function(){return this._wpIndices||(this._wpIndices=this._route.waypointIndices||this._findWaypointIndices()),this._wpIndices}}),t.Routing.mapzenLine=function(i,e){return new t.Routing.MapzenLine(i,e)},module.exports=t.Routing}()}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[3,4,5]);
Example #23
0
export async function polyline (start, end) {
  const json = await route(start, end)
  return decodePolyline(json.trip.legs[0].shape)
    .map((c) => [c[1] / 10, c[0] / 10]) // Mapzen or Mapbox is encoding/decoding wrong?
}
 this.directions.routes.forEach(function (route) {
     route.geometry = {
         type: "LineString",
         coordinates: polyline.decode(route.geometry, 6).map(function (c) { return c.reverse(); })
     };
 });
Example #25
0
                var afterRequest = (err, res) => {
                    if (err) return cb(err);
                    var json;

                    var headers = new Set(table.raw()[0]);

                    if (res.body.length) {
                        json = JSON.parse(res.body);
                    }

                    if (headers.has('status')) {
                        got.status = json.status.toString();
                    }

                    if (headers.has('message')) {
                        got.message = json.status_message;
                    }

                    if (headers.has('#')) {
                        // comment column
                        got['#'] = row['#'];
                    }

                    var subMatchings = [],
                        turns = '',
                        route = '',
                        duration = '',
                        annotation = '',
                        geometry = '',
                        OSMIDs = '';


                    if (res.statusCode === 200) {
                        if (headers.has('matchings')) {
                            subMatchings = json.matchings.filter(m => !!m).map(sub => sub.matched_points);
                        }

                        if (headers.has('turns')) {
                            if (json.matchings.length != 1) throw new Error('*** Checking turns only supported for matchings with one subtrace');
                            turns = this.turnList(json.matchings[0].instructions);
                        }

                        if (headers.has('route')) {
                            if (json.matchings.length != 1) throw new Error('*** Checking route only supported for matchings with one subtrace');
                            route = this.wayList(json.matchings[0]);
                        }

                        if (headers.has('duration')) {
                            if (json.matchings.length != 1) throw new Error('*** Checking duration only supported for matchings with one subtrace');
                            duration = json.matchings[0].duration;
                        }

                        if (headers.has('annotation')) {
                            if (json.matchings.length != 1) throw new Error('*** Checking annotation only supported for matchings with one subtrace');
                            annotation = this.annotationList(json.matchings[0]);
                        }

                        if (headers.has('geometry')) {
                            if (json.matchings.length != 1) throw new Error('*** Checking geometry only supported for matchings with one subtrace');
                            geometry = json.matchings[0].geometry;
                        }

                        if (headers.has('OSM IDs')) {
                            if (json.matchings.length != 1) throw new Error('*** CHecking annotation only supported for matchings with one subtrace');
                            OSMIDs = this.OSMIDList(json.matchings[0]);
                        }
                    }

                    if (headers.has('turns')) {
                        got.turns = turns;
                    }

                    if (headers.has('route')) {
                        got.route = route;
                    }

                    if (headers.has('duration')) {
                        got.duration = duration.toString();
                    }

                    if (headers.has('annotation')) {
                        got.annotation = annotation.toString();
                    }

                    if (headers.has('geometry')) {
                        if (this.queryParams['geometries'] === 'polyline')
                            got.geometry = polyline.decode(geometry).toString();
                        else
                            got.geometry = geometry;
                    }

                    if (headers.has('OSM IDs')) {
                        got['OSM IDs'] = OSMIDs;
                    }

                    var ok = true;
                    var encodedResult = '',
                        extendedTarget = '';

                    var q = d3.queue();

                    var testSubMatching = (sub, si, scb) => {
                        if (si >= subMatchings.length) {
                            ok = false;
                            q.abort();
                            scb();
                        } else {
                            var sq = d3.queue();

                            var testSubNode = (ni, ncb) => {
                                var node = this.findNodeByName(sub[ni]),
                                    outNode = subMatchings[si][ni];

                                if (this.FuzzyMatch.matchLocation(outNode, node)) {
                                    encodedResult += sub[ni];
                                    extendedTarget += sub[ni];
                                } else {
                                    encodedResult += util.format('? [%s,%s]', outNode[0], outNode[1]);
                                    extendedTarget += util.format('%s [%d,%d]', node.lat, node.lon);
                                    ok = false;
                                }
                                ncb();
                            };

                            for (var i=0; i<sub.length; i++) {
                                sq.defer(testSubNode, i);
                            }

                            sq.awaitAll(scb);
                        }
                    };

                    row.matchings.split(',').forEach((sub, si) => {
                        q.defer(testSubMatching, sub, si);
                    });

                    q.awaitAll(() => {
                        if (ok) {
                            if (headers.has('matchings')) {
                                got.matchings = row.matchings;
                            }

                            if (headers.has('timestamps')) {
                                got.timestamps = row.timestamps;
                            }
                        } else {
                            got.matchings = encodedResult;
                            row.matchings = extendedTarget;
                        }

                        cb(null, got);
                    });
                };
Example #26
0
var polyline = require('polyline')

// returns an array of lat, lon pairs
polyline.decode('_p~iF~ps|U_ulLnnqC_mqNvxq`@');
Example #27
0
                var afterRequest = (err, res) => {
                    if (err) return cb(err);
                    var headers = new Set(table.raw()[0]);

                    for (var k in row) {
                        var match = k.match(/param:(.*)/);
                        if (match) {
                            if (row[k] === '(nil)') {
                                params[match[1]] = null;
                            } else if (row[k]) {
                                params[match[1]] = [row[k]];
                            }
                            got[k] = row[k];
                        }
                    }

                    var json;
                    got.code = 'unknown';
                    if (res.body.length) {
                        json = JSON.parse(res.body);
                        got.code = json.code;
                    }

                    if (headers.has('status')) {
                        got.status = json.code;
                    }

                    if (headers.has('message')) {
                        got.message = json.message;
                    }

                    if (headers.has('geometry')) {
                        if (this.queryParams['geometries'] === 'polyline') {
                            got.geometry = polyline.decode(json.trips[0].geometry).toString();
                        } else if (this.queryParams['geometries'] === 'polyline6') {
                            got.geometry = polyline.decode(json.trips[0].geometry, 6).toString();
                        } else {
                            got.geometry = json.trips[0].geometry.coordinates;
                        }
                    }

                    if (headers.has('#')) {
                        // comment column
                        got['#'] = row['#'];
                    }

                    var subTrips;
                    var trip_durations;
                    var trip_distance;
                    if (res.statusCode === 200) {
                        if (headers.has('trips')) {
                            subTrips = json.trips.filter(t => !!t).map(t => t.legs).map(tl => Array.prototype.concat.apply([], tl.map((sl, i) => {
                                var toAdd = [];
                                if (i === 0) toAdd.push(sl.steps[0].intersections[0].location);
                                toAdd.push(sl.steps[sl.steps.length-1].intersections[0].location);
                                return toAdd;
                            })));
                        }
                        if(headers.has('durations')) {
                            var all_durations = json.trips.filter(t => !!t).map(t => t.legs).map(tl => Array.prototype.concat.apply([], tl.map(sl => {
                                return sl.duration;
                            })));
                            trip_durations = all_durations.map( a => a.reduce(add, 0));
                        }
                        if(headers.has('distance')) {
                            var all_distance = json.trips.filter(t => !!t).map(t => t.legs).map(tl => Array.prototype.concat.apply([], tl.map(sl => {
                                return sl.distance;
                            })));
                            trip_distance = all_distance.map( a => a.reduce(add, 0));
                        }
                    }

                    var ok = true,
                        encodedResult = '';

                    if (json.trips) row.trips.split(',').forEach((sub, si) => {
                        if (si >= subTrips.length) {
                            ok = false;
                        } else {
                            // TODO: Check all rotations of the round trip
                            for (var ni=0; ni<sub.length; ni++) {
                                var node = this.findNodeByName(sub[ni]),
                                    outNode = subTrips[si][ni];
                                if (this.FuzzyMatch.matchLocation(outNode, node)) {
                                    encodedResult += sub[ni];
                                } else {
                                    ok = false;
                                    encodedResult += util.format('? [%s,%s]', outNode[0], outNode[1]);
                                }
                            }
                        }
                    });

                    if (ok) {
                        got.trips = row.trips;
                        got.via_points = row.via_points;
                    } else {
                        got.trips = encodedResult;
                    }

                    got.durations = trip_durations;
                    got.distance = trip_distance;

                    for (var key in row) {
                        if (this.FuzzyMatch.match(got[key], row[key])) {
                            got[key] = row[key];
                        }
                    }

                    cb(null, got);
                };
Example #28
0
function createGeojson(rawData,callback){

  featureCollection.features = [];

  for(var i=0;i<rawData.length;i++) {
    coordinates = rawData[i].trippolyline;
    coordinates2 = rawData[i].nextpolyline;
    coordinates = polyline.decode(coordinates);
    coordinates2 = polyline.decode(coordinates2);

    var feature = {
      type:"Feature",
      properties:{},
      geometry:{
        type:"LineString",
        coordinates:[]
      }
    }

    var feature2 = {
      type:"Feature",
      properties:{},
      geometry:{
        type:"LineString",
        coordinates:[]
      }
    }

    feature.properties.medallion = rawData[i].medallion;
    feature.properties.passengers = rawData[i].passengers;
    feature.properties.fare = rawData[i].fare;
    feature.properties.paymenttype = rawData[i].paymenttype;
    feature.properties.surcharge = rawData[i].surcharge;
    feature.properties.mtatax = rawData[i].mtatax;
    feature.properties.tip = rawData[i].tip;
    feature.properties.tolls = rawData[i].tolls;
    feature.properties.total = rawData[i].total;
    feature.properties.pickuptime = rawData[i].pickuptime;
    feature.properties.dropofftime = rawData[i].dropofftime;
    feature.properties.nextpickuptime = rawData[i].nextpickuptime;
    feature.properties.key = rawData[i].key;
    feature.properties.hasfare = true;



    feature2.properties.pickuptime = rawData[i].dropofftime;
    feature2.properties.dropofftime = rawData[i].nextpickuptime;
    feature2.properties.key = rawData[i].key;
    feature2.properties.hasfare = false;



    for(var j=0;j<coordinates.length;j++){

      var coord = [coordinates[j][1],coordinates[j][0]]
//create a feature
feature.geometry.coordinates.push(coord);
};

for(var j=0;j<coordinates2.length;j++){

  var coord = [coordinates2[j][1],coordinates2[j][0]]
//create a feature
feature2.geometry.coordinates.push(coord);
};




featureCollection.features.push(feature);
featureCollection.features.push(feature2);
}

callback(featureCollection);

}
Example #29
0
                var afterRequest = (err, res) => {
                    if (err) return cb(err);
                    var json;

                    var headers = new Set(table.raw()[0]);

                    got.code = 'unknown';
                    if (res.body.length) {
                        json = JSON.parse(res.body);
                        got.code = json.code;
                    }


                    if (headers.has('status')) {
                        got.status = json.status.toString();
                    }

                    if (headers.has('message')) {
                        got.message = json.status_message;
                    }

                    if (headers.has('#')) {
                        // comment column
                        got['#'] = row['#'];
                    }

                    var subMatchings = [''],
                        turns = '',
                        route = '',
                        duration = '',
                        annotation = '',
                        geometry = '',
                        OSMIDs = '',
                        alternatives = '';


                    if (res.statusCode === 200) {
                        if (headers.has('matchings')) {
                            subMatchings = [];

                            // find the first matched
                            let start_index = 0;
                            while (start_index < json.tracepoints.length && json.tracepoints[start_index] === null) start_index++;

                            var sub = [];
                            let prev_index = null;
                            for(var i = start_index; i < json.tracepoints.length; i++){
                                if (json.tracepoints[i] === null) continue;

                                let current_index = json.tracepoints[i].matchings_index;

                                if(prev_index !== current_index) {
                                    if (sub.length > 0) subMatchings.push(sub);
                                    sub = [];
                                    prev_index = current_index;
                                }

                                sub.push(json.tracepoints[i].location);
                            }
                            subMatchings.push(sub);
                        }

                        if (headers.has('turns')) {
                            if (json.matchings.length != 1) throw new Error('*** Checking turns only supported for matchings with one subtrace');
                            turns = this.turnList(json.matchings[0].instructions);
                        }

                        if (headers.has('route')) {
                            if (json.matchings.length != 1) throw new Error('*** Checking route only supported for matchings with one subtrace');
                            route = this.wayList(json.matchings[0]);
                        }

                        if (headers.has('duration')) {
                            if (json.matchings.length != 1) throw new Error('*** Checking duration only supported for matchings with one subtrace');
                            duration = json.matchings[0].duration;
                        }

                        // annotation response values are requested by 'a:{type_name}'
                        var found = false;
                        headers.forEach((h) => { if (h.match(/^a:/)) found = true; });
                        if (found) {
                            if (json.matchings.length != 1) throw new Error('*** Checking annotation only supported for matchings with one subtrace');
                            annotation = this.annotationList(json.matchings[0]);
                        }

                        if (headers.has('geometry')) {
                            if (json.matchings.length != 1) throw new Error('*** Checking geometry only supported for matchings with one subtrace');
                            geometry = json.matchings[0].geometry;
                        }

                        if (headers.has('alternatives')) {
                            alternatives = this.alternativesList(json);
                        }
                    }

                    if (headers.has('turns')) {
                        got.turns = turns;
                    }

                    if (headers.has('route')) {
                        got.route = route;
                    }

                    if (headers.has('duration')) {
                        got.duration = duration.toString();
                    }

                    // if header matches 'a:*', parse out the values for *
                    // and return in that header
                    headers.forEach((k) => {
                        let whitelist = ['duration', 'distance', 'datasources', 'nodes', 'weight'];
                        if (k.match(/^a:/)) {
                            let a_type = k.slice(2);
                            if (whitelist.indexOf(a_type) == -1)
                                return cb(new Error('Unrecognized annotation field:' + a_type));
                            if (!annotation[a_type])
                                return cb(new Error('Annotation not found in response: ' + a_type));
                            got[k] = annotation[a_type];
                        }
                    });

                    if (headers.has('geometry')) {
                        if (this.queryParams['geometries'] === 'polyline') {
                            got.geometry = polyline.decode(geometry).toString();
                        } else if (this.queryParams['geometries'] === 'polyline6') {
                            got.geometry = polyline.decode(geometry,6).toString();
                        } else {
                            got.geometry = geometry.coordinates;
                        }
                    }

                    if (headers.has('OSM IDs')) {
                        got['OSM IDs'] = OSMIDs;
                    }

                    if (headers.has('alternatives')) {
                        got['alternatives'] = alternatives;
                    }
                    var ok = true;
                    var encodedResult = '',
                        extendedTarget = '';

                    var testSubMatching = (sub, si) => {
                        var testSubNode = (ni) => {
                            var node = this.findNodeByName(sub[ni]),
                                outNode = subMatchings[si][ni];

                            if (this.FuzzyMatch.matchLocation(outNode, node)) {
                                encodedResult += sub[ni];
                                extendedTarget += sub[ni];
                            } else {
                                if (outNode != null) {
                                    encodedResult += util.format('? [%s,%s]', outNode[0], outNode[1]);
                                } else {
                                    encodedResult += '?';
                                }
                                extendedTarget += util.format('%s [%d,%d]', node.lat, node.lon);
                                ok = false;
                            }
                        };

                        for (var i=0; i<sub.length; i++) {
                            testSubNode(i);
                        }
                    };

                    if (headers.has('matchings')) {
                        if (subMatchings.length != row.matchings.split(',').length) {
                            return cb(new Error('*** table matchings and api response are not the same'));
                        }

                        row.matchings.split(',').forEach((sub, si) => {
                            testSubMatching(sub, si);
                        });
                    }

                    if (ok) {
                        if (headers.has('matchings')) {
                            got.matchings = row.matchings;
                        }

                        if (headers.has('timestamps')) {
                            got.timestamps = row.timestamps;
                        }
                    } else {
                        got.matchings = encodedResult;
                        row.matchings = extendedTarget;
                    }

                    cb(null, got);
                };
Example #30
0
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){function corslite(url,callback,cors){var sent=false;if(typeof window.XMLHttpRequest==="undefined"){return callback(Error("Browser not supported"))}if(typeof cors==="undefined"){var m=url.match(/^\s*https?:\/\/[^\/]*/);cors=m&&m[0]!==location.protocol+"//"+location.domain+(location.port?":"+location.port:"")}var x=new window.XMLHttpRequest;function isSuccessful(status){return status>=200&&status<300||status===304}if(cors&&!("withCredentials"in x)){x=new window.XDomainRequest;var original=callback;callback=function(){if(sent){original.apply(this,arguments)}else{var that=this,args=arguments;setTimeout(function(){original.apply(that,args)},0)}}}function loaded(){if(x.status===undefined||isSuccessful(x.status))callback.call(x,null,x);else callback.call(x,x,null)}if("onload"in x){x.onload=loaded}else{x.onreadystatechange=function readystate(){if(x.readyState===4){loaded()}}}x.onerror=function error(evt){callback.call(this,evt||true,null);callback=function(){}};x.onprogress=function(){};x.ontimeout=function(evt){callback.call(this,evt,null);callback=function(){}};x.onabort=function(evt){callback.call(this,evt,null);callback=function(){}};x.open("GET",url,true);x.send(null);sent=true;return x}if(typeof module!=="undefined")module.exports=corslite},{}],2:[function(require,module,exports){var polyline={};function encode(coordinate,factor){coordinate=Math.round(coordinate*factor);coordinate<<=1;if(coordinate<0){coordinate=~coordinate}var output="";while(coordinate>=32){output+=String.fromCharCode((32|coordinate&31)+63);coordinate>>=5}output+=String.fromCharCode(coordinate+63);return output}polyline.decode=function(str,precision){var index=0,lat=0,lng=0,coordinates=[],shift=0,result=0,byte=null,latitude_change,longitude_change,factor=Math.pow(10,precision||5);while(index<str.length){byte=null;shift=0;result=0;do{byte=str.charCodeAt(index++)-63;result|=(byte&31)<<shift;shift+=5}while(byte>=32);latitude_change=result&1?~(result>>1):result>>1;shift=result=0;do{byte=str.charCodeAt(index++)-63;result|=(byte&31)<<shift;shift+=5}while(byte>=32);longitude_change=result&1?~(result>>1):result>>1;lat+=latitude_change;lng+=longitude_change;coordinates.push([lat/factor,lng/factor])}return coordinates};polyline.encode=function(coordinates,precision){if(!coordinates.length)return"";var factor=Math.pow(10,precision||5),output=encode(coordinates[0][0],factor)+encode(coordinates[0][1],factor);for(var i=1;i<coordinates.length;i++){var a=coordinates[i],b=coordinates[i-1];output+=encode(a[0]-b[0],factor);output+=encode(a[1]-b[1],factor)}return output};if(typeof module!==undefined)module.exports=polyline},{}],3:[function(require,module,exports){(function(global){(function(){"use strict";var L=typeof window!=="undefined"?window.L:typeof global!=="undefined"?global.L:null;L.Routing=L.Routing||{};L.Routing.Mapzen.Formatter=L.Class.extend({options:{units:"metric",unitNames:{meters:"m",kilometers:"km",yards:"yd",miles:"mi",hours:"h",minutes:"mín",seconds:"s"},language:"en",roundingSensitivity:1,distanceTemplate:"{value} {unit}"},initialize:function(options){L.setOptions(this,options)},formatDistance:function(d){var un=this.options.unitNames,v,data;if(this.options.units==="imperial"){d=d*1e3;d=d/1.609344;if(d>=1e3){data={value:this._round(d)/1e3,unit:un.miles}}else{data={value:this._round(d/1.76),unit:un.yards}}}else{v=d;data={value:v>=1?v:v*1e3,unit:v>=1?un.kilometers:un.meters}}return L.Util.template(this.options.distanceTemplate,data)},_round:function(d){var pow10=Math.pow(10,(Math.floor(d/this.options.roundingSensitivity)+"").length-1),r=Math.floor(d/pow10),p=r>5?pow10:pow10/2;return Math.round(d/p)*p},formatTime:function(t){if(t>86400){return Math.round(t/3600)+" h"}else if(t>3600){return Math.floor(t/3600)+" h "+Math.round(t%3600/60)+" min"}else if(t>300){return Math.round(t/60)+" min"}else if(t>60){return Math.floor(t/60)+" min"+(t%60!==0?" "+t%60+" s":"")}else{return t+" s"}},formatInstruction:function(instr,i){return instr.instruction},getIconName:function(instr,i){switch(instr.type){case 1:return"kStart";case 2:return"kStartRight";case 3:return"kStartLeft";case 4:return"kDestination";case 5:return"kDestinationRight";case 6:return"kDestinationLeft";case 7:return"kBecomes";case 8:return"kContinue";case 9:return"kSlightRight";case 10:return"kRight";case 11:return"kSharpRight";case 12:return"kUturnRight";case 13:return"kUturnLeft";case 14:return"kSharpLeft";case 15:return"kLeft";case 16:return"kSlightLeft";case 17:return"kRampStraight";case 18:return"kRampRight";case 19:return"kRampLeft";case 20:return"kExitRight";case 21:return"kExitLeft";case 22:return"kStayStraight";case 23:return"kStayRight";case 24:return"kStayLeft";case 25:return"kMerge";case 26:return"kRoundaboutEnter";case 27:return"kRoundaboutExit";case 28:return"kFerryEnter";case 29:return"kFerryExit"}},_getInstructionTemplate:function(instr,i){return instr.instruction+" "+instr.length}})})()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],4:[function(require,module,exports){(function(global){(function(){"use strict";var L=typeof window!=="undefined"?window.L:typeof global!=="undefined"?global.L:null;var corslite=require("corslite");var polyline=require("polyline");L.Routing=L.Routing||{};L.Routing.Mapzen=L.Class.extend({initialize:function(accessToken,transitmode,costingOptions,otherOptions,options){L.Util.setOptions(this,options||{timeout:30*1e3});this._accessToken=accessToken;this._transitmode=transitmode;this._costingOptions=costingOptions;this._hints={locations:{}}},route:function(waypoints,callback,context,options){var timedOut=false,wps=[],url,timer,wp,i;options=options||{};url=this.buildRouteUrl(waypoints,options);timer=setTimeout(function(){timedOut=true;callback.call(context||callback,{status:-1,message:"Time out."})},this.options.timeout);for(i=0;i<waypoints.length;i++){wp=waypoints[i];wps.push({latLng:wp.latLng,name:wp.name||"",options:wp.options||{}})}corslite(url,L.bind(function(err,resp){var data;clearTimeout(timer);if(!timedOut){if(!err){data=JSON.parse(resp.responseText);this._routeDone(data,wps,callback,context)}else{console.log("Error : "+err.response);callback.call(context||callback,{status:err.status,message:err.response})}}},this),true);return this},_routeDone:function(response,inputWaypoints,callback,context){var coordinates,alts,actualWaypoints,i;context=context||callback;if(response.trip.status!==0){callback.call(context,{status:response.status,message:response.status_message});return}var insts=[];var coordinates=[];var shapeIndex=0;for(var i=0;i<response.trip.legs.length;i++){var coord=polyline.decode(response.trip.legs[i].shape,6);for(var k=0;k<coord.length;k++){coordinates.push(coord[k])}for(var j=0;j<response.trip.legs[i].maneuvers.length;j++){var res=response.trip.legs[i].maneuvers[j];res.distance=response.trip.legs[i].maneuvers[j]["length"];res.index=shapeIndex+response.trip.legs[i].maneuvers[j]["begin_shape_index"];insts.push(res)}shapeIndex+=response.trip.legs[i].maneuvers[response.trip.legs[i].maneuvers.length-1]["begin_shape_index"]}actualWaypoints=this._toWaypoints(inputWaypoints,response.trip.locations);alts=[{name:this._trimLocationKey(inputWaypoints[0].latLng)+" , "+this._trimLocationKey(inputWaypoints[1].latLng),unit:response.trip.units,transitmode:this._transitmode,coordinates:coordinates,instructions:insts,summary:response.trip.summary?this._convertSummary(response.trip.summary):[],inputWaypoints:inputWaypoints,waypoints:actualWaypoints,waypointIndices:this._clampIndices([0,response.trip.legs[0].maneuvers.length],coordinates)}];if(response.hint_data){this._saveHintData(response.hint_data,inputWaypoints)}callback.call(context,null,alts)},_saveHintData:function(hintData,waypoints){var loc;this._hints={checksum:hintData.checksum,locations:{}};for(var i=hintData.locations.length-1;i>=0;i--){loc=waypoints[i].latLng;this._hints.locations[this._locationKey(loc)]=hintData.locations[i]}},_toWaypoints:function(inputWaypoints,vias){var wps=[],i;for(i=0;i<vias.length;i++){wps.push(L.Routing.waypoint(L.latLng([vias[i]["lat"],vias[i]["lon"]]),"name",{}))}return wps},buildRouteUrl:function(waypoints,options){var serviceUrl="https://valhalla.mapzen.com";var locs=[],locationKey,hint;var costingOptions=this._costingOptions;for(var i=0;i<waypoints.length;i++){var loc;locationKey=this._locationKey(waypoints[i].latLng).split(",");if(i===0||i===waypoints.length-1){loc={lat:parseFloat(locationKey[0]),lon:parseFloat(locationKey[1]),type:"break"}}else{loc={lat:parseFloat(locationKey[0]),lon:parseFloat(locationKey[1]),type:"through"}}locs.push(loc)}var params=JSON.stringify({locations:locs,costing:this._transitmode,costing_options:costingOptions});return serviceUrl+"/route?json="+params+"&api_key="+this._accessToken},_locationKey:function(location){return location.lat+","+location.lng},_trimLocationKey:function(location){var lat=location.lat;var lng=location.lng;var nameLat=Math.floor(location.lat*1e3)/1e3;var nameLng=Math.floor(location.lng*1e3)/1e3;return nameLat+" , "+nameLng},_convertSummary:function(route){return{totalDistance:route.length,totalTime:route.time}},_convertInstructions:function(instructions){console.log("is this even necessary?");var result=[],i,instr,type,driveDir;for(i=0;i<instructions.length;i++){instr=instructions[i];type=this._drivingDirectionType(instr[0]);driveDir=instr[0].split("-");if(type){result.push({type:type,distance:instr[2],time:instr[4],road:instr[1],direction:instr[6],exit:driveDir.length>1?driveDir[1]:undefined,index:instr[3]})}}return result},_clampIndices:function(indices,coords){var maxCoordIndex=coords.length-1,i;for(i=0;i<indices.length;i++){indices[i]=Math.min(maxCoordIndex,Math.max(indices[i],0))}}});L.Routing.mapzen=function(accessToken,transitmode,options){return new L.Routing.Mapzen(accessToken,transitmode,options)};module.exports=L.Routing.Mapzen})()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{corslite:1,polyline:2}]},{},[4,3]);