如何将字符串地址传递到传单路由机,以根据字符串地址获得方向

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

本文关键字:地址 字符串 方向 路由 址传 单路由      更新时间:2023-09-26

好吧,我正在使用传单api,然后我发现了一个非常好的支持插件,称为传单路由机,用于显示从a到B的地址,路由很好。

然而,传单路由机在传递latlng时工作良好,但在传递地址时不工作,所以有人能告诉我它是如何工作的吗?我知道以下链接上的房产信息:所以航路点有一个叫做name的属性,但没有;我不知道如何使用它来提供地址a和地址B

这是一个显示新西兰奥克兰市的代码。。。。并试图传递地址,但不起作用

< 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>
请记住,还可以将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);

但这并没有对其进行地理编码。相反,它只是填充路点文本框。您仍然需要在每个框上点击enter(或通过js触发它)才能运行geocoder。

另一种选择是手动从地理编码器获取数据,并在设置航路点之前创建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);

更新以涵盖评论中的问题

可以通过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);