How to pass string address to leaflet routing machine to get direction based on string address?

Jim*_*mil 2 javascript leaflet

Well, I am using leaflet api and then I found a very nice supporting plugin called leaflet routing machine for showing address from A to B with nice route.

However, leaflet routing machine working fine with passing of latlng but not working with passing address so can anyone tell how it can work as I know property information on following link: So routing waypoint have property called name but don;t know how to use it to provide address a and address B

Here is a code which shows new Zealand Auckland city....and trying to pass address but doesn't work

< script >

  var mymap = L.map('mapid', {
    center: [-36.85625, 174.76141],
    zoom: 13
  });

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.yourkey', {

  attribution: 'Log Sample',
  id: 'mapbox.streets'
}).addTo(mymap);
//L.Control.geocoder().addTo(mymap);
L.Routing.control({
  waypoints: [
    //L.latLng(-36.87178, 174.753),
    //L.latLng(-36.84514, 174.76493)
    L.name("12 Morning Star place, Auckland"),
    L.name("198 Dominion road, Mount Roskill, Auckland")
  ],
  routeWhileDragging: false
}).addTo(mymap); < /script>
Run Code Online (Sandbox Code Playgroud)

And*_*sko 5

据记得,您也可以将L.Routing.Waypoint对象传递给waypoints

所以,你的代码看起来像:

....
var geocoder = L.Control.Geocoder.nominatim()

L.Routing.control({
  geocoder: geocoder,
  waypoints: [
    //L.latLng(-36.87178, 174.753),
    //L.latLng(-36.84514, 174.76493)
    L.Routing.waypoint(null,"12 Morning Star place, Auckland"),
    L.Routing.waypoint(null,"198 Dominion road, Mount Roskill, Auckland")
  ],
  routeWhileDragging: false,
}).addTo(mymap);
Run Code Online (Sandbox Code Playgroud)

但这又不会对其进行地理编码。而只是填充航点文本框。您仍然需要在每个框上按 Enter(或通过 js 触发)以运行地理编码器。

另一种选择是在设置航点之前手动从地理编码器中获取数据并创建L.Routing.WaypointL.LatLng对象

geocoder.geocode('Montreal', function(a, b) {
    // depending on geocoder results may be either in a or b 
    console.log(a);
    // choose the best result here. probably the first one in array
    // create waypoint object
    var wpt = L.Routing.waypoint(L.latLng(lat, lng), name)
    waypoints.push(wpt);
})

...

// setting waypoints
routingControl.setWaypoints(waypoints);
Run Code Online (Sandbox Code Playgroud)

更新以涵盖评论中的问题

带有弹出窗口的自定义标记可以通过L.Routing.Plan. 您的L.Routing.control对象可以像这样初始化:

var geocoder = L.Control.Geocoder.nominatim(),
    waypoints = [], // can be populated later
    routeControl = L.Routing.control({
        plan: L.Routing.plan(waypoints, {
                createMarker: function(i, wp) {
                    return L.marker(wp.latLng, {
                        draggable: true
                    }).bindPopup("Some data for popup");
                },
            geocoder: geocoder,
            routeWhileDragging: false,
        })
    }).addTo(map);
Run Code Online (Sandbox Code Playgroud)