0

I trying to move the created movable marker so that it points to the results of the Locate() function.

This would allow the recalculation of the other closest markers in the datasource.

Presently, this works only when I manually drag the movable matker.

I can't seem to be able to get the coordinates of the location found and move the marker there.

Thanks for any help!

Here's my code:

    <!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>
Jeester
  • 1
  • 3

1 Answers1

0

Is L.control.locate really needed here? Why not just call map.locate() after binding an callback to locationfound with map.on('locationfound, dostuff) Your function receives the results of the geolocation and can proceed from there.

snkashis
  • 2,951
  • 1
  • 18
  • 35
  • I tried removing the control and to move the marker (m) but it still doesn;t move. – Jeester May 14 '15 at 20:29
  • Can you post a fiddle where we can see all this in action? – snkashis May 14 '15 at 21:03
  • Here's the fiddle. https://jsfiddle.net/Jeester/dh125gvd/5/ I made the changed you said. I'm trying to move the original marker (or simply initiate it when location is known) in order to keep the tracking of the distance related to the other markers. The datasource is wrong on this example but it works as an exampolke. – Jeester May 14 '15 at 22:32
  • You know you have a javascript error here in play right? Inside the `locationfound` callback, you call `setGeoJSON` on `myLayer`, which is undefined. – snkashis May 14 '15 at 22:55
  • Sorry about that! Here's a new Fiddle ,all cleaned up! https://jsfiddle.net/Jeester/9chjpda6/2/ – Jeester May 15 '15 at 00:38
  • So a problem I'm seeing here is...you reference ` marker.feature.properties.type` & `marker.feature.properties.name` in the eachLayer loop code..yet those those are not available in any of your properties hashes...`description`,`id`,`marker-color`,`marker-size`,`marker-symbol`,`marker-zoom` & `title` are though. – snkashis May 15 '15 at 18:44
  • Thanks for taking the time to help. I took the code from the MapBox examples and tried to adapt it to my need. I reverted it back to the original code and this is now fixed in my previous fiddle. It almost does what I want. I'm looking for a listing that changes depending of the proximity of the Locate marker. This example is doing that but with a dragable marker. So I told myself the easiest thing might be to move the dragable marker to the Locate.Position. Not sure if this is the best approach, – Jeester May 16 '15 at 03:10
  • No problem. I reworked your fiddle and I think I have it working how you wanted now. Notice I removed a lot of the extraneous locate options. https://jsfiddle.net/4L49vw3k/1/ – snkashis May 16 '15 at 16:05