user1717344
user1717344

Reputation: 133

Getting "Uncaught TypeError: Cannot read property 'lat' of undefined" with mapbox and leaflet

I'm new to mapbox and leaflet, and I apologize in advance if this a bit basic. I'm trying to load a map with markers. However, I'm getting this error and I'm not sure how to debug it. self.map.addLayer(connector) is throwing the error. Does anyone know what I'm doing wrong? Thanks.

buildMap: function() {
  console.log('buildMap() function...');
  var lat, lng,
  self = this;

  navigator.geolocation.getCurrentPosition(function(data) {
    var lat, lng, latlng;
    lat = data['coords']['latitude'];
    lng = data['coords']['longitude'];
    debugger;

    self.map.remove();
    self.map = new L.mapbox.map('map', 'bmy78.map-z27ovm6p')
                            .setView(new L.LatLng(lat, lng), 15);

    console.log('lat', lat);
    console.log('lng', lng);

    // use mapbox
    mapboxUrl = "http://a.tiles.mapbox.com/v3/bmy78.map-z27ovm6p.jsonp";
    wax.tilejson(mapboxUrl, function(tilejson) {
      connector = new wax.leaf.connector(tilejson);
      self.map.addLayer(connector);
    });
  });

Upvotes: 3

Views: 10015

Answers (1)

A. STEFANI
A. STEFANI

Reputation: 6737

If you want to prevent Map to be "undefined".

First declare your map variable as public js variable (in the head of your html document and outside any function)

var map;

Next, build the map inside the document ready function (to be sure that leaflet is properly load),

$( document ).ready(function() {
  map= L.mapbox.map('map', 'bmy78.map-z27ovm6p')
  //here you try to ask the user position then setView to map
}

You may now access the map variable without any "undefined error",

Best regards

Upvotes: 2

Related Questions