11

It produces an error when i use turf on my mapbox specifically this line: var nearestBuilding = turf.nearest(currentLocation, geoJson);. I use mapbox-gl and the turf to get the nearest building. It works when i input the data manually without object.push() but i need the information from the database.

var object = [];

for (var x = 0; x < json.length; x++) {
  var 
    image = json[x].image == '' ? '' : "<div style='text-align:center;'><img src='" + json[x].image + "' width='100' height='75' /></div>",
    number = json[x].contact == '' ? '' : "<br/>" + json[x].contact,
    details = json[x].details == '' ? '' : '<br/>' + '<a href="{{ url('restaurants-and - cafe') }}/' + json[x].details + '">More Details</a>';

  object.push({
    type: 'Feature',
    properties: {
      title: json[x].name,
      description: image + json[x].content + number + details,
      cuisine: json[x].cuisine,
      id: json[x].id,
      icon: {
        iconUrl: json[x].icon,
        iconSize: [20, 50],
        iconAnchor: [10, 5],
        popAnchor: [0, 0],
        className: 'custom-map-marker'
      }
    },
    geometry: {
      type: 'Point',
      coordinates: [json[x].longitude, json[x].latitude]
    }
  });
}

var geoJson = {
  type: 'FeatureCollection',
  features: object
};

var currentLocation = {
  type: 'Feature',
  geometry: {
    type: 'Point',
    coordinates: [121.048282, 14.548682]
  }
};

map.on('load', function () {
  var el = document.createElement('div');
  el.className = 'currLocMarker';

  marker = new mapboxgl.Marker(el, { offset: [-50 / 2, -50 / 2] })
    .setLngLat(currentLocation.geometry.coordinates)
    .addTo(map);

  var nearestBuilding = turf.nearest(currentLocation, geoJson);
  var distance = turf.distance(currentLocation, nearestBuilding);
});
n1stre
  • 5,856
  • 4
  • 20
  • 41
Merida
  • 368
  • 1
  • 3
  • 13
  • 7
    I would guess that your `json[x].longitude` and `json[x].latitude` are strings and not numbers. you can try `+json[x].longitude` to cast the strings to numbers. – mollymerp Aug 18 '17 at 03:06
  • @mollymerp it now works when i used +. thank you! – Merida Aug 22 '17 at 03:52

0 Answers0