Home > Enterprise >  Using leaflet mapbox tiles with Vue 2 results in an error attempting to read lat
Using leaflet mapbox tiles with Vue 2 results in an error attempting to read lat

Time:06-30

I have a sample project at https://github.com/ericg-vue-questions/leaflet-test

I am following a Building an interactive map with Vue and Leaflet tutorial.

The relevant code is:

<template>
  <div id="container">
    <div id="mapContainer"></div>
  </div>
</template>

<script>
import "leaflet/dist/leaflet.css";
import L from "leaflet";
//
// obtain a mapbox token from https://account.mapbox.com/access-tokens/
// and then create token.js in ./src/components with the following content:
//
//    const token = "<your token>";
//    export { token };
//
import {token} from "./token.js";

export default {
  name: "Map",

  data() {
    return{
      center: [37,7749, -122,4194]
    }
  },

  methods: {
    setupLeafletMap: function () {
      const mapDiv = L.map("mapContainer").setView(this.center, 13);
      L.tileLayer(
        `https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=${token}`,
        {
          attribution: 'Map data (c) <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery (c) <a href="https://www.mapbox.com/">Mapbox</a>',
          maxZoom: 18,
          id: "mapbox/streets-v11",
          accessToken: `${token}`,
        }
      ).addTo(mapDiv);
    },
  },

  mounted() {
    this.setupLeafletMap();
  },
};
</script>

<style scoped>
  #mapContainer {
    width: 500px;
    height: 500px;
  }
</style>

As I understand it, this should be enough to start displaying map tiles.

When the code is executed, it results in the error:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in mounted hook: "TypeError: Cannot read properties of null (reading 'lat')"

found in

---> <Map> at src/components/LeafletTest.vue
       <HelloWorld> at src/components/HelloWorld.vue
         <App> at src/App.vue
           <Root>

TypeError: Cannot read properties of null (reading 'lat')
    at Object.project (leaflet-src.js?e11e:1685:1)
    at Object.latLngToPoint (leaflet-src.js?e11e:1522:1)
    at NewClass.project (leaflet-src.js?e11e:3949:1)
    at NewClass._getNewPixelOrigin (leaflet-src.js?e11e:4472:1)
    at NewClass._move (leaflet-src.js?e11e:4191:1)
    at NewClass._resetView (leaflet-src.js?e11e:4153:1)
    at NewClass.setView (leaflet-src.js?e11e:3175:1)
    at VueComponent.setupLeafletMap (LeafletTest.vue?232a:30:1)
    at VueComponent.mounted (LeafletTest.vue?232a:44:1)
    at invokeWithErrorHandling (vue.runtime.esm.js?2b0e:1863:1)

I am not sure what is going wrong or how to fix it. What do I need to change so the map tiles will be loaded.

CodePudding user response:

You have to use floats as lat long.

like: center: [37.7749, -122.4194]

  • Related