0

我正在使用带有地理编码器(ESRI)和路由机的传单地图。我添加了两个标记,比如说我的家和我的工作

var marker_work = L.marker([50.27, 19.03], { title: 'MyWork'}).addTo(map)
.bindPopup("work").openPopup();

var marker_home = L.marker([50.10, 18.4], { title: 'MyHome'}).addTo(map)
.bindPopup("home").openPopup();

这是一个示例小提琴: https ://jsfiddle.net/21nmk8so/1/

如何将此标记/点添加为 ControlGeocoder 的预定义位置?我想在搜索中使用它们并用作路线计算的起点/终点。

同一问题的另一个示例:如何添加带有纬度/经度的自定义假城市,并能够搜索(查找路线)往返该城市。

4

1 回答 1

1

我不知道这是否是最好的解决方案,但它正在工作:创建一个覆盖该geocode函数的自定义地理编码器类。在那里,您可以覆盖结果函数并将建议应用于结果。

L.CustomGeocoder = L.Control.Geocoder.Nominatim.extend({
    suggestions: [],
    setSuggestions(arr){
      this.suggestions = arr;
    },
    createSuggestionFromMarker(marker){
      this.suggestions.push({name: marker.options.title, center: marker.getLatLng()});
    },
    getResultsOfSuggestions(query){
      var results = [];
      this.suggestions.forEach((point)=>{
        if(point.name.indexOf(query) > -1){
          point.center = L.latLng(point.center);
          point.bbox = point.center.toBounds(100);
          results.push(point);
        }
      });
      return results;
    },
    geocode(query, resultFnc, context) {
      var that = this;
      var callback = function(results){
        var sugg = that.getResultsOfSuggestions(query);
        resultFnc.call(this,sugg.concat(results));
      }
      L.Control.Geocoder.Nominatim.prototype.geocode.call(that,query, callback, context);
    }
  })

然后你必须使用新的 Geocoder 类:

var geocoder = new L.CustomGeocoder({});

var control = L.Routing.control({
  waypoints: [],
  router: new L.Routing.osrmv1({
    language: 'en',
    profile: 'car'
  }),
  geocoder: geocoder
}).addTo(map);

最后,您可以在标记上添加建议,并在or上添加title选项:createSuggestionFromMarker(marker)setSuggestions(arr)

var suggestions = [
  {
    name: 'Test Car 1',
    center: [50.27, 19.03]
  },
  {
    name: 'Test Car 2',
    center: [50.10, 18.4]
  }
];
geocoder.setSuggestions(suggestions);

var marker_work = L.marker([50.27, 19.03], { title: 'MyWork'}).addTo(map);
var marker_home = L.marker([50.10, 18.4], { title: 'MyHome'}).addTo(map);

geocoder.createSuggestionFromMarker(marker_work);
geocoder.createSuggestionFromMarker(marker_home);

更新,使用标记 Ref 而不是修复 latlng

更改这两个函数,然后引用标记,它总是从标记的当前位置开始搜索:


    createSuggestionFromMarker(marker){
      this.suggestions.push({name: marker.options.title, marker: marker});
    },
    getResultsOfSuggestions(query){
      var results = [];
      this.suggestions.forEach((point)=>{
        if(point.name.indexOf(query) > -1){
            if(point.marker){
            point.center = point.marker.getLatLng();
          }
          point.center = L.latLng(point.center);
          point.bbox = point.center.toBounds(100);
          results.push(point);
        }
      });
      return results;
    },

当您拖动标记时,您可以在演示中对此进行测试

https://jsfiddle.net/falkedesign/hu25jfd1/

于 2021-01-03T22:15:49.420 回答