Giter Site home page Giter Site logo

lrm-mapzen's Introduction

Mapzen is shutting down its services including Turn-by-turn. Read more at https://mapzen.com/blog/shutdown/

npm version

Add support for Mapzen Turn-by-Turn routing in Leaflet Routing Machine

Mapzen Turn-by-Turn is an open-source routing service with dynamic run-time costing that lets you integrate automobile, bicycle, pedestrian, or multimodal navigation into a web or mobile application.

Use this plug-in to create a Leaflet map that has a route line between map locations (also known as waypoints), a text narrative of maneuvers to perform on the route, distances along your route and estimated travel times, and the ability to drag the route start and endpoints to get a different path.

With lrm-mapzen, Mapzen Turn-by-Turn is substituted for the default routing service used in Leaflet Routing Machine. You need to install the lrm-mapzen plug-in and obtain an API key from mapzen.com/developers.

Get started with lrm-mapzen

Follow along with this tutorial to build a map with lrm-mapzen.

Download lrm-mapzen and insert a reference to the JavaScript file into your page right after the line where it loads Leaflet Routing Machine:

[...]
<script src="leaflet-routing-machine.js"></script>
<script src="lrm-mapzen.js"></script>
[...]

Also, include the stylesheet. This can replace the default leaflet-routing-machine.css provided by LRM, since the Mapzen plug-in includes its own styles and icons.

<link rel="stylesheet" href="leaflet.routing.mapzen.css">

Insert your Mapzen API key for the placeholder text (mapzen-xxxxxx) and a routing options object to at least include the costing mode (auto, bicycle, pedestrian, or multimodal). Note that no additional options are needed for formatter.

var map = L.map('map');

L.Routing.control({
  // [...] See MapzenTurn-by-Turn API documentation for other options
  router: L.Routing.mapzen('mapzen-xxxxxx', {
    costing:'auto'
  }),
  formatter: new L.Routing.mapzenFormatter()
}).addTo(map);

If you want to include additional costing options to help define the the route and estimated time along the path, you can pass a costing option object as one of router parameters. You can also include options for directions in order to change the language, distance units or narrative guidance production. See the Mapzen Turn-by-Turn API documentation for more information on the available options.

L.Routing.control({
  router: L.Routing.mapzen('mapzen-xxxxxx', {
    costing: "bicycle",
    costing_options: {
      bicycle: {
        bicycle_type: "Road",
        cycling_speed: "17.0",
        use_roads: "0.1"
      },
    },
    directions_options: {
      language: 'en-US'
    }
  }),
  formatter: new L.Routing.mapzenFormatter(),
}).addTo(map);

With themultimodal costing mode, you can set costing options for preferences for taking buses or rail lines or having to make transfers. If you include a date_time, you can request a transit route departing at a certain time, for example. See the Mapzen Turn-by-Turn API documentation for more information on the available options.

L.Routing.control({
  router: L.Routing.mapzen('mapzen-xxxxxx', {
    // you need to pass mapzenLine as routeLine to router to see subroutes of transit routing.
    // you can skip routeLine if you don't want to use subroutes.
    routeLine: function (route, options) { return L.Routing.mapzenLine(route, options); },
    costing: "multimodal",
    date_time: {
      type: 1,
      value: "2016-05-10T08:00"
    }
  }),
  formatter: new L.Routing.mapzenFormatter(),
}).addTo(map);

See the Leaflet Routing Machine documentation and Mapzen Turn-by-Turn API documentation for more information.

Use lrm-mapzen with npm and Browserify

The Mapzen plug-in can be installed using npm instead of downloading the script manually:

npm install --save lrm-mapzen

Once the Mapzen plug-in is installed, update the router and formatter instances to tell the Leaflet Routing Machine to use Mapzen’s engine.

var L = require('leaflet');
require('leaflet-routing-machine');
require('lrm-mapzen');

var map = L.map('map');

L.Routing.control({
  router: L.Routing.mapzen('mapzen-xxxxxx', {costing:'auto'}),
  formatter: new L.Routing.mapzenFormatter()
}).addTo(map);

For router, insert your Mapzen Turn-by-Turn API key and a routing options object to at least include the routing mode (such as auto, bicycle, pedestrian, or multimodal); see the Mapzen Turn-by-Turn API documentation for more information. (Note that no additional options are needed for formatter.)

You can also change the route costing mode after the router is created. Say you had different transportation options on your map and wanted to change costing to bicycle when that button is clicked:

var rr = L.Routing.mapzen('mapzen-xxxxxx', {costing:'auto'});
[...]
bikeButton.onClick: function () {
  rr.route({costing: "bicycle"});
}

Run a local example

If you want to run your lrm-mapzen plug-in locally for testing and development purposes:

  • Install lrm-mapzen through npm or download the contents of the lrm-mapzen repo
  • Get your API key from mapzen.com/developers
  • Paste it into the example's index.js and choose the transportation/costing mode (auto, bicycle, or pedestrian)
  • Start a local web server (such as python -m SimpleHTTPServer or the local server you prefer)
  • Go to http://localhost:8000/examples in your browser (all assets needed to run Mapzen are in the /examples folder)

lrm-mapzen's People

Contributors

alex-outdoor avatar bcamper avatar easherma avatar eelcocramer avatar glennon avatar hanbyul-here avatar jessecrocker avatar kdiluca avatar kevinkreiser avatar louh avatar luizfonseca avatar migurski avatar perliedman avatar rmglennon avatar skorasaurus avatar stevendlander avatar tim-field avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lrm-mapzen's Issues

change too general class name

  • lrm-mapzen is currently using .info as a class name to display the costing option. This is too general, it might conflict with others

Example with auto (car) vs bus routing.

Generally, auto options/costs are relatively straightforward. The "auto" vs "bus" could be interesting if you can find a route where large tour buses would not be allowed. For example, certain residential streets or possibly hills that are too steep (I'm not sure which factors the "bus" considers). In SF, there are some streets with signs that do not allow tour buses with more than 8 passengers.

Sub-Route (transfer) bug

When there's a transfer, the associated maneuver will be a part of 2 different subRoutes (with a different color associated to it).
@hanbyul-here I'll take a look as well

Can't set the language to spanish

Hi, according to the documentation spanish language is supported now (actually I helped to the Odin project) however I couldn't figure out how to set it.
I use mapzen router with leaflet-routing-machine.
I am facing two problems after doing the routing :

  • the name of the origin/destination dissapear, it shows the word "name" (image attached)
  • the texts are in english.

Thanks in advance for any tips.

Best!
Here's the code:

function crearControlRouting() {

routeControl = L.Routing.control({

     router: L.Routing.mapzen('valhalla-A4rESty', {costing:'bicycle'}),
     formatter: new L.Routing.mapzenFormatter({language:'es-Es'}),

    plan: L.Routing.plan([], {
            geocoder: L.Control.Geocoder.nominatim({
            geocodingQueryParams: { countrycodes: 'uy'}
          }),
          reverseWaypoints: true,
          city:'Montevideo',
          language: 'sp'
        }),
    lineOptions: {
        styles:
            [
                {color: 'black', opacity: 0.15, weight: 9}, //sombra
                {color: 'white', opacity: 0.8, weight: 6}, // Contorno
                {color: 'red', opacity: 1, weight: 4}] // Centro
   },
   summaryTemplate:  '<h2>Trayectoria: {name}</h2><h3>Distancia: {distance}</h3>',
   language: 'sp',        
    waypointMode:  'snap',
    collapsible: true  //nuevo
}).addTo(mapa);

}

irab

Change units to miles

Hi.

Can you please tell me where to put the units: "miles" parameter in the L.Routing.control?

I've tried all sorts of options, but the route is still in kilometers.

Thank you

Add possibility to use your own Valhalla Server

I am hosting my own Valhalla server and would like to use this plugin with it.
My server has does not require an API key and rejects the requests made by this plugin.

I could add this functionality and make a PR for it, if you let me.

Problem with pedestrian mode

Hey guys !

Nice work first ;)

So i'm having an issue with LRM and Mapzen, my website is able to calculate the routing in auto, bicycle mode, but not in the only mode I really need, pedestrian.

This is the code I'm using :
var routing = L.Routing.control({ router: L.Routing.mapzen('valhalla-TC63npX', {costing:'pedestrian'}), formatter: new L.Routing.mapzenFormatter(), waypoints: routing_poi_list, routeWhileDragging: false, collapsible: true, draggableWaypoints: false, addWaypoints: false }).addTo(map);

And the error (sorry it's in french) :
Error : No path could be found for input lrm-mapzen.min.js:1:3757 erreur de syntaxe

No path could be found : I don't understand why because it works in other modes.
Syntax error ? Why ?

Thanks for your help !

Making the turn by turn example work with requirejs (r.js)

I have tried lot of ways to load this example (https://mapzen.com/documentation/mobility/turn-by-turn/add-routing-to-a-map/) using requirejs and it works using the shim :

 shim: {
   'mapbox': {
     exports: 'L'
   },
   'routing-machine': {
     deps: ['tangram'],
     exports: 'routing-machine'
   },
   'mapzen': {
     deps: ['routing-machine', 'tangram'],
     exports: 'mapzen'
   }
}

But after running r.js -o app/build.js it throws

Uncaught TypeError: Cannot read property 'mapzen' of undefined

This is my build.js file

({
 baseUrl: './',
 out: 'dist/app/main.js',
 optimize: 'none',
 include: ['main'],
 wrap: true,
 preserveLicenseComments: false,
 wrapShim: true,
 paths: {
   // Core Libraries
   'pusher': 'utils/pusher.min',
   'moment': 'vendor/moment/min/moment.min',
   'locales': 'vendor/moment/min/locales.min',
   'jquery': 'vendor/jquery/dist/jquery',
   'underscore': 'vendor/lodash/lodash',
   'backbone': 'vendor/backbone/backbone',
   'marionette': 'vendor/marionette/lib/core/backbone.marionette',
   // Plugins
   'backbone-mongodb': 'vendor/backbone-mongodb/backbone-mongodb.amd',
   'fastclick': 'vendor/fastclick/lib/fastclick',
   'backbone.validateAll': 'vendor/Backbone.validateAll/src/javascripts/Backbone.validateAll',
   'text': 'vendor/text/text',
   'backbone.wreqr': 'vendor/backbone.wreqr/lib/backbone.wreqr',
   'backbone.eventbinder': 'vendor/backbone.eventbinder/lib/amd/backbone.eventbinder',
   'backbone.babysitter': 'vendor/backbone.babysitter/lib/backbone.babysitter',
   'backbone.syphon': 'vendor/backbone.syphon/lib/backbone.syphon.min',
   'tpl': 'vendor/underscore-tpl/dist/underscore-tpl.min',
   'backboneRouteFilter': 'vendor/backbone-route-filter/backbone-route-filter-min',
   'backboneCrossdomain': 'vendor/backbone.crossdomain/Backbone.CrossDomain',
   'underscore.string': 'vendor/underscore.string/dist/underscore.string.min',
   'backbone.radio': 'vendor/backbone.radio/build/backbone.radio.min',
   'radio.shim': 'utils/radio.shim',
   'backbone.epoxy': 'vendor/backbone.epoxy/backbone.epoxy',
   'marionette.vdom': 'utils/marionette.vdom',
   'notie': 'vendor/notie/dist/notie.min',
   'pace': 'vendor/PACE/pace.min',
   'async': 'vendor/async/dist/async.min',
   'mapzen': 'utils/lrm-mapzen',
   'mapbox': 'utils/mapbox',
   'tangram': 'vendor/tangram/dist/tangram.debug',
   'routing-machine': 'vendor/leaflet-routing-machine/dist/leaflet-routing-machine',
   'simplebar': 'utils/simplebar',
   'dexie': 'vendor/dexie/dist/dexie.min',
   'sortable': 'vendor/Sortable/Sortable'
 }
})

Could you provide an example of this please?

Returning turn-by-turn data from a route.

I have been using this library to get the maneuver data from a set route. Although I have no issues setting up the map and route, I have a hard time accessing the object/string that holds where the vehicle needs to turn at each point (left, right, etc) so I can use it with a GPS. Getting it as a string or JSON would be perfect, I just don't know what to do at this point.

I have found that there is a way to do this from the documentation but I either don't understand it or am trying to do it the wrong way so I was wondering if someone more experienced could help me out or give me some ideas on how I might me able to pull this off.

Here's my code so far for the script (all of the files are attached bellow):

// Create a map. Targets div with id 'map'.
var map = L.map('map');

var layer = Tangram.leafletLayer({
  scene: 'https://raw.githubusercontent.com/tangrams/refill-style/gh-pages/refill-style.yaml',
  attribution: '<a href="https://mapzen.com/tangram" target="_blank">Tangram</a> | <a href="http://www.openstreetmap.org/about" target="_blank">&copy; OSM contributors | <a href="https://mapzen.com/" target="_blank">Mapzen</a>',
}); // End of layer.

// Add's the styles and attributions to the map.
layer.addTo(map);

// Set the default view of the map (Bristol).
// No need to use this when a route is being diplayed.
//map.setView([51.4545,-2.5879], 16);

// Set's a route and add's it to the map, it requires two points and their respective latitute and longitude.
L.Routing.control({
      waypoints: [
        L.latLng(51.4998,-2.5468),
        L.latLng(51.5055,-2.5603)
      ]
    }).addTo(map);


// I used a log to try and find out which object has the turn-by-turn data. No luck so far.
console.log(L.Routing.mapzen('mapzen-apikey', `{costing:'auto'}));

Project files of what I have so far:
mapzen_turns_incomplete.zip

Thank you for reading, I would be extremely grateful if someone gave me a hand with this.

Configure language?

Hi, I'd like to know if there's the possibilty to change the language. If so, where's the part of the code to tackle? Thanks so much in advance. Best!

Change markers

Hi!
I can't find the way to change the marker of starting and arrival point of a route. Is it possible?

routing-icon.png doesn't exist for leaflet-routing-collapse-btn

The collapsible button icon doesn't exist in the project files. routing-icon.png is not distributed.

.leaflet-routing-container-hide .leaflet-routing-collapse-btn {
    position: relative;
    left: 4px;
    top: 4px;
    display: block;
    width: 26px;
    height: 23px;
    background-image: url('routing-icon.png');
}

Consider how to handle routing with multiple break points where some are along the way

If you try to route with more than two break points and one is in between, it will convert anything in between from a break to a through location. This behavior is as-designed, because you can modify the route interactively by dragging.

When loading points from a list, though, this gives unexpected results. This was a support request from a user (see below for original email).

Snips of a repro case @dgearhart worked out:

URL based on the information in the test file:
http://valhalla.mapzen.com/route?json={"locations":[{"lat":40.749706,"lon":-73.991562,"street":"West 32nd Street"},{"lat":40.744370,"lon":-73.990379,"street":"West 26th Street"},{"lat":40.738121,"lon":-73.990883,"street":"East 18th Street"},{"lat":40.730949,"lon":-73.991432,"street":"Wanamaker Place"}],"costing":"auto","directions_options":{"units":"miles"}}

URL sent from the test tool:
https://valhalla.mapzen.com/route?json={"locations":[{"lat":40.749706,"lon":-73.991562,"type":"break"},{"lat":40.74437,"lon":-73.990379,"type":"through"},{"lat":40.730949,"lon":-73.991432,"type":"break"}],"costing":"auto","directions_options":{"units":"miles"}}

cc @hanbyul-here @dnesbitt61


Original question from a user (see support ticket 1333):

All my points are set to ‘Break’ because the route could be very complicated so I wantet to have stops along the way.

When I’m using for example the osrm-router, my instructions are connected to my waypoints on the map which is the expected behaviour. However, when using the mapzen-routing, the itinerary seems to skip some waypoints, say ‘you have reached your destination’ when they are still meters away from the point and don’t even go to the last point.

This seems to be a problem when every point is a break point. If I set the point to ‘through’, that problem seems to be non-existing, but there is no way for me to know in the itinary if I’ve reached a waypoint along the way.

Change marker

Hi!
I can't find the way to change the marker of starting and arrival point of a route. Is it possible?

How to get a route without using the control?

Hi, I think the question is very explanatory, I will explain a little more anyway. I want to find the route between 2 points. One of the point is nearest one to the user position and the another one is the user position. It worked while I was using the leaflet-routing-machine.js default's router.
routes = L.Routing.osrmv1({addWaypoints: false});

However I changed it to routes: L.Routing.mapzen('mapzen-xxxxxx', {costing: 'bicycle'}); and it doesn't work, the router tunrs to be null.

The error message:
Uncaught TypeError: Cannot read property 'route' of null

Thanks in advance for any clue. Best!

This is the code so far.

function rutaAB(latA, latB)  
{
    var waypoints = [];
    var coords = [];
    var waysp = [];

    waypoints.length = 0;
    coords.length = 0;
    waysp.length = 0;
    if ((latA != null) && (latB != null))
    {
        var latlngA = L.Routing.waypoint(latA);
        var latlngB = L.Routing.waypoint(latB);
        waypoints.push(latlngA);
        waypoints.push(latlngB);

        var routes = null;

        routes: L.Routing.mapzen('mapzen-3indRB', {costing: 'bicycle'});
        // routes is null when using  L.Routing.mapzen
        //routes = L.Routing.osrmv1({addWaypoints: false}); it works

        routes.route(waypoints, function(err, routes) {
             if (line) {
                 mapa.removeLayer(line);
             }

             if (err) {
                 console.log(err);
             }
             else {

                 coords = routes[0].coordinates;
                 waysp = routes[0].waypoints;
                 line = L.Routing.line(routes[0],{styles:[{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: '#1652F4', opacity: 1, weight: 3}]}).addTo(mapa);

                 var distanciaCerc = convertirKM(routes[0].summary.totalDistance);
                 popup = L.popup({offset: L.point(0, -30)})
                        .setLatLng(latB)
                        .setContent('<p>Distancia: <b>' + distanciaCerc + '</b></p>')
                        .openOn(mapa);

             }
       });

    }
    else
    {
        alert("Se necesita el par Origen-Destino para calcular la ruta");

    }

}


showAlternatives not showing

when using the lrm control, like so:

LRM.control({
    waypoints: points,
    geocoder: gCoder,
    routeWhileDragging: routeDrag,
    router: L.Routing.valhalla(apiKey, "auto", { "serviceUrl": serviceUrl }),
    showAlternatives: true,
    formatter: new LRMValhalla.Formatter()
}).addTo(map);

no alternative routes are shown. Is this functionality currently supported? none of the examples seemed to show it. we have fed in control points that show an alternative route using an alternate routing service.

thoughts?

No 'Access-Control-Allow-Origin' to valhalla.mapzen.com

Hi, I began to use mapzen to do the routing, in this case without using the control
I am not able to do this because the not Allowed origin message. The weird thing is that it works when it is used with the leaflet routing machine control. This is the code and the message.

Thanks in advance

function rutaAB(latA, latB)  // 
{
    var waypoints = [];
    var coords = [];
    var waysp = [];


    waypoints.length = 0;
    coords.length = 0;
    waysp.length = 0;
    if ((latA != null) && (latB != null))
    {

        var latlngA = L.Routing.waypoint(latA);
        var latlngB = L.Routing.waypoint(latB);

        waypoints.push(latlngA);
        waypoints.push(latlngB);

        var routes = null;

        routes = L.Routing.mapzen({addWaypoints: false});

        routes.route(waypoints, function(err, routes) {
             if (line) {
                 mapa.removeLayer(line);
             }

             if (err) {
                 console.log(err);
             }
             else {

                 coords = routes[0].coordinates;
                 waysp = routes[0].waypoints;
                 line = L.Routing.line(routes[0],{styles:[{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: '#1652F4', opacity: 1, weight: 3}]}).addTo(mapa);

                 var distanciaCerc = convertirKM(routes[0].summary.totalDistance);
                 popup = L.popup({offset: L.point(0, -30)})
                        .setLatLng(latB)
                        .setContent('<p>Distancia: <b>' + distanciaCerc + '</b></p>')
                        .openOn(mapa);

             }
       });

    }
    else
    {
        alert("Se necesita el par Origen-Destino para calcular la ruta");

    }

}


routing

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.