Javascript 调用Locate函数后移动标记

Javascript 调用Locate函数后移动标记,javascript,mapbox,marker,locate,Javascript,Mapbox,Marker,Locate,我试图移动创建的可移动标记,使其指向Locate()函数的结果 这将允许重新计算数据源中其他最近的标记 目前,这只在我手动拖动可移动的matker时起作用 我似乎无法获得找到的位置的坐标并将标记移动到那里 谢谢你的帮助 这是我的密码: <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Reorder marker list based on proximity

我试图移动创建的可移动标记,使其指向Locate()函数的结果

这将允许重新计算数据源中其他最近的标记

目前,这只在我手动拖动可移动的matker时起作用

我似乎无法获得找到的位置的坐标并将标记移动到那里

谢谢你的帮助

这是我的密码:

    <!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Reorder marker list based on proximity</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.9/mapbox.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.9/mapbox.css' rel='stylesheet' />
<style>
  body { margin:0; padding:0; }
  #map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
  .info {
    background:#fff;
    position: fixed;
    width:90%;
    top:70%;
    right:5%;
    left:5%;
    bottom: 5%;
    border-radius:2px;
    max-height:30%;
    overflow:auto;
    }
    .info .item {
      display:block;
      border-bottom:1px solid #eee;
      padding:5px;
      text-decoration:none;
      }
      .info .item small { color:#888; }
      .info .item:hover,
      .info .item.active { background:#f8f8f8; }
      .info .item:last-child { border-bottom:none; }
</style>

<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.2.0/leaflet-omnivore.min.js'></script>

<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-locatecontrol/v0.42.0/L.Control.Locate.min.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-locatecontrol/v0.42.0/L.Control.Locate.mapbox.css' rel='stylesheet' />
<!--[if lt IE 9]>
<link href='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-locatecontrol/v0.42.0/L.Control.Locate.ie.css' rel='stylesheet' />
<![endif]-->


<div id='map' class='map'></div>
<div id='info' class='info'></div>

<script>
L.mapbox.accessToken = 'pk.eyJ1IjoiamZnaWFyZCIsImEiOiJ6S09PVU5vIn0.kn_-BVWarxfNjT1hak0kyA';
var map = L.mapbox.map('map', 'jfgiard.9dee89eb')
  .setView([51.953608, 36.776667], 4);
var info = document.getElementById('info');


// create control and add to map
var lc = L.control.locate({
    position: 'topleft',  // set the location of the control
    drawCircle: true,  // controls whether a circle is drawn that shows the uncertainty about the location
    follow: false,  // follow the user's location
    setView: true, // automatically sets the map view to the user's location, enabled if `follow` is true
    keepCurrentZoomLevel: true, // keep the current map zoom level when displaying the user's location. (if `false`, use maxZoom)
    stopFollowingOnDrag: false, // stop following when the map is dragged if `follow` is true (deprecated, see below)
    remainActive: false, // if true locate control remains active on click even if the user's location is in view.
    markerClass: L.circleMarker, // L.circleMarker or L.marker
    circleStyle: {},  // change the style of the circle around the user's location
    markerStyle: {},
    followCircleStyle: {},  // set difference for the style of the circle around the user's location while following
    followMarkerStyle: {},
    icon: 'fa fa-map-marker',  // class for icon, fa-location-arrow or fa-map-marker
    iconLoading: 'fa fa-spinner fa-spin',  // class for loading icon
    circlePadding: [0, 0], // padding around accuracy circle, value is passed to setBounds
    metric: true,  // use metric or imperial units
    onLocationError: function(err) {alert(err.message)},  // define an error callback function
    onLocationOutsideMapBounds:  function(context) { // called when outside map boundaries
            alert(context.options.strings.outsideMapBoundsMsg);
    },
    showPopup: true, // display a popup when the user click on the inner marker
    strings: {
        title: "Show me where I am",  // title of the locate control
        popup: "You are within {distance} {unit} from this point",  // text to appear if user clicks on circle
        outsideMapBoundsMsg: "You seem located outside the boundaries of the map" // default message for onLocationOutsideMapBounds
    },
    locateOptions: {}  // define location options e.g enableHighAccuracy: true or maxZoom: 10
}).addTo(map);

// Creates a single, draggable marker on the page.
var m = L.marker(new L.LatLng(51.953608, 36.776667), {
    icon: L.mapbox.marker.icon({
        'marker-color': '#000000',
        'marker-size': 'large'
    }),
    draggable: true
}).bindPopup('Drag me around the map to simulate GeoLocalization!').addTo(map);

// Repopulate the features layer in the menu listing based on the dragged markers proximity to them.
// console.log(marker.getLatLng());
m.on('dragend', function() {
    populateListing();
});

// Load the features from the CSV files.
var features = omnivore.csv('NMOandHTC.csv')
    .on('ready', function(layer) {
        // Customizing marker styles based on an attribute.
        this.eachLayer(function(marker) {
            if (marker.toGeoJSON().properties.type === 'National Member Organization') {
                // The argument to L.mapbox.marker.icon is based on the simplestyle-spec: see that specification for a full description of options.
                marker.setIcon(L.mapbox.marker.icon({
                    'marker-color': '#e31837',
                    'marker-size': 'medium'
                }));
            } else {
                marker.setIcon(L.mapbox.marker.icon({
                    'marker-color': '#616265',
                    'marker-size': 'small'
                }));
            }
            // Bind a popup to each icon based on the same properties
            marker.bindPopup(marker.toGeoJSON().properties.name + '<br>' + marker.toGeoJSON().properties.country);
        });
    })
    .addTo(map);

map.on('ready', function() {
    // Display the tooltip after the marker has been added to the map.
    m.openPopup();
});

// When the features layer is ready (added to the map), run populateListing.
features.on('ready', populateListing);


function populateListing() {
    // Clear out the listing container first.
    info.innerHTML = '';
    var listings = [];

    // Build a listing of markers
    features.eachLayer(function(marker) {
        // Draggable marker coordinates.
        var home = m.getLatLng();
        var metresToMiles = 0.000621371192;
        var distance = (metresToMiles * home.distanceTo(marker.getLatLng())).toFixed(1);

        var link = document.createElement('a');
        link.className = 'item';
        link.href = '#';
        link.setAttribute('data-distance', distance);

        // Populate content from each markers object.
        link.innerHTML = marker.feature.properties.type + '<br />' + marker.feature.properties.name + '<br />' +
            '<small>' + distance + ' mi. away</small>';

        link.onclick = function() {
            if (/active/.test(this.className)) {
                this.className = this.className.replace(/active/, '').replace(/\s\s*$/, '');
            } else {
                var siblings = info.getElementsByTagName('a');
                for (var i = 0; i < siblings.length; i++) {
                    siblings[i].className = siblings[i].className
                    .replace(/active/, '').replace(/\s\s*$/, '');
                };
                this.className += ' active';

                // When a menu item is clicked, animate the map to center
                // its associated marker and open its popup.
                map.panTo(marker.getLatLng());
                marker.openPopup();
            }
            return false;
        };

        listings.push(link);
    });

    // Sort the listing based on the
    // assigned attribute, 'data-listing'
    listings.sort(function(a, b) {
        return a.getAttribute('data-distance') - b.getAttribute('data-distance');
    });

    listings.forEach(function(listing) {
        info.appendChild(listing);
    });
}
</script>
</body>
</html>

基于邻近性对标记列表重新排序
正文{margin:0;padding:0;}
#映射{位置:绝对;顶部:0;底部:0;宽度:100%;}
.info{
背景:#fff;
位置:固定;
宽度:90%;
最高:70%;
右:5%;
左:5%;
底部:5%;
边界半径:2px;
最高高度:30%;
溢出:自动;
}
.info.item{
显示:块;
边框底部:1px实心#eee;
填充物:5px;
文字装饰:无;
}
.info.item小{颜色:#888;}
.info.item:悬停,
.info.item.active{背景:#f8f8;}
.info.item:最后一个子项{边框底部:无;}
L.mapbox.accessToken='pk.eyj1ijoiamznawfyzcisimeioj6s09pvu5vin0.kn_u2;-bvwarxfnjt1hakkya';
var map=L.mapbox.map('map','jfgiard.9dee89eb')
.setView([51.953608,36.776667],4);
var info=document.getElementById('info');
//创建控件并添加到映射
var lc=L.control.locate({
位置:'左上',//设置控件的位置
drawCircle:true,//控制是否绘制显示位置不确定性的圆
follow:false,//跟随用户的位置
setView:true,//自动将地图视图设置为用户的位置,如果'follow'为true,则启用该选项
keepCurrentZoomLevel:true,//显示用户位置时保持当前地图缩放级别。(如果“false”,则使用maxZoom)
StopFollowindRag:false,//如果'follow'为true,则在拖动地图时停止跟随(已弃用,请参见下文)
remainActive:false,//如果为true,则即使用户的位置在视图中,单击时定位控件仍保持活动状态。
marker类:L.circleMarker,//L.circleMarker或L.marker
circleStyle:{},//更改用户位置周围圆圈的样式
markerStyle:{},
followCircleStyle:{},//在跟随时设置用户位置周围圆圈的样式差异
followMarkerStyle:{},
图标:“fa地图标记”,//图标类、fa位置箭头或fa地图标记
iconload:'fa-spinner-fa-spin',//用于加载图标的类
circlePadding:[0,0],//在精度圆周围填充,值传递给立根
公制:true,//使用公制或英制单位
onLocationError:function(err){alert(err.message)},//定义一个错误回调函数
onLocationOutsideMapBounds:函数(上下文){//在映射边界之外时调用
警报(context.options.strings.OutsideMapBoundsMSSG);
},
showPopup:true,//当用户单击内部标记时显示弹出窗口
字符串:{
标题:“显示我在哪里”//locate控件的标题
弹出窗口:“您离此点在{distance}{unit}范围内”//如果用户单击圆圈,将显示文本
outsideMapBoundsMsg:“您似乎位于地图边界之外”//onLocationOutsideMapBounds的默认消息
},
locateOptions:{}//定义位置选项,例如EnableHighAccurance:true或maxZoom:10
}).addTo(地图);
//在页面上创建一个可拖动的标记。
var m=L.标记(新的L.标记(51.953608,36.776667){
图标:L.mapbox.marker.icon({
“标记颜色”:“000000”,
“标记大小”:“大”
}),
德拉格布尔:是的
}).bindpoppop('在地图上拖动我来模拟地理定位!').addTo(地图);
//根据拖动的标记与要素图层的接近程度,在菜单列表中重新填充要素图层。
//console.log(marker.getLatLng());
m、 on('dragend',function(){
populateListing();
});
//从CSV文件加载功能。
var features=omnivore.csv('NMOandHTC.csv')
.on('ready',功能(层){
//基于属性自定义标记样式。
this.eachLayer(函数(标记器){
if(marker.toGeoJSON().properties.type===‘国家成员组织’){
//L.mapbox.marker.icon的参数基于simplestyle规范:有关选项的完整说明,请参阅该规范。
marker.setIcon(L.mapbox.marker.icon({
“标记颜色”:“e31837”,
“标记大小”:“中等”
}));
}否则{
marker.setIcon(L.mapbox.marker.icon({
“标记颜色”:“616265”,
“标记大小”:“小”
}));
}
//基于相同属性将弹出窗口绑定到每个图标
marker.bindpoop(marker.toGeoJSON().properties.name+'
'+marker.toGeoJSON().properties.country); }); }) .addTo(地图); map.on('ready',function(){ //将标记添加到地图后显示工具提示。 m、 openPopup(); }); //要素图层准备就绪(添加到地图)后,运行populateListing。 功能。on('ready',populateListing); 函数populateListing(){ //首先清除列表容器。 info.innerHTML=''; var清单=[]; //建立一个标记列表 功能。每个图层(功能(标记){ //可拖动标记坐标。 var home=m.getLatLng(); var metresToMiles=0.000621371192; var distance=(metresToMiles*home.distanceTo(marker.getLatLng()).toFixed(1); var link=document.createElement('a'); link.className='item'; link.href='#'; link.setAttribute('data-distance',distance); //从每个标记对象填充内容。 link.innerHTML=marker.feature.properties.type+'
'+marker.feature.properties.name+'
'+