I have a mapbox map, initialized with the outdoors-v9 style (tried other styles, same behavior). When I add a layer to the map - a marker or a geojson source and zoom the map, the style changes or breaks, I'm not sure which.
This is the map before the zoom
and after the zoom
here are the functions that init the map and add markers
mapboxgl.accessToken = "pk.*******";
buildMap: function() {
const _self = this;
_self.map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/outdoors-v9",
center: [-95.712891, 37.09024],
zoom: 3
});
_self.map.on('load', function() {
_self.map.addSource('route', {
'type': 'geojson',
'data': {
"type": "FeatureCollection",
"features": []
}
});
_self.map.addLayer({
'id': 'route',
'source': 'route',
'type': 'line',
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': '#47576A',
'line-width': 3
}
});
});
}
...
const coords = [addressData.longitude, addressData.latitude];
const marker = new mapboxgl.Marker().setLngLat(coords).addTo(this.map);
I am using Vue.js to render the map. Mapbox version v0.45.0
Any help or leads are highly appreciated
Vue data() properties are reactive, they have getters and setters, so, when loading map object or adding vector tiles layer (geojson), Vue tries to add getters & setters to the map & map.layers which causes vue & vue-dev-tools to crash and mess up the map.
If you enable any raster layer, it would work successfully because raster tiles are loaded via the mapbox.css whereas vector tiles being geojson, are added to the map object.
Easiest solution would be to define a non-reactive variable in vue and then re-use it everywhere.
// edit: A correct/recommended way to set non-reactive data: GitHub link
Seems the issue was related with the fact that I'm pushing the marker instance to an observable (a vuejs data field). After pushing the marker instance to an array, the issue disappeared. This comment doesn't really answer why this happens, but hope it helps someone else that might face the same issue
I just faced this issue and realized that I didn't follow the documentation exactly as it was described (jumped right on to coding without reading properly). And the documentation says:
Storing Map object
Take note that it's generally bad idea to add to Vuex or component's
data anything but primitive types and plain objects. Vue adds getters
and setters to every property, so if you add Map object to Vuex store
or component data, it may lead to weird bugs. If you want to store map
object, store it as non-reactive property like in example below.
The problem was that I had also registered "map" inside the "data" object of my Vue component. But in the example code it's not declared in data, only in the "create" function.
https://soal.github.io/vue-mapbox/guide/basemap.html#map-loading
After hours spent on this problem, here is my working solution to access map instance from a store (thanks to https://github.com/vuejs/vue/issues/2637#issuecomment-331913620):
const state = reactive({
map: Object.freeze({ wrapper: /* PUT THE MAP INSTANCE HERE */ });
});
Here is an example with Vue Composition Api:
index.js
import { reactive, computed } from "#vue/composition-api";
export const state = reactive({
map: null
});
export const setMap = (map) => {
state.map = Object.freeze({ wrapper: map});
};
export const getMap = computed(() => state.map.wrapper);
export const initMap = (event) => {
setMap(event.map);
// now you can access to map instance from the "getMap" getter!
getMap.value.addSource("satellite-source", {
type: "raster",
url: "mapbox://mapbox.satellite",
});
getMap.value.addLayer({
id: "satellite-layer",
type: "raster",
source: "satellite-source"
});
};
App.vue
<template>
<MglMap :accessToken="..." :mapStyle="..." #load="onMapLoaded" />
</template>
<script>
import { defineComponent } from "#vue/composition-api";
import { MglMap } from "vue-mapbox";
import { initMap } from "./index.js";
export default defineComponent({
components: {
MglMap
},
setup() {
const onMapLoaded = (event) => {
initMap(event);
}
return { onMapLoaded };
}
});
</script>
I've got the same error.
This happens if you either put the map or the marker on an reactive vue.js instance.
Short and quick answer.
Explanation is similar to #mlb's answer. So you freeze the object to prevent the map from disorientated and for any actions done to the map, call back the data with an extra Object key which in case is 'wrapper'.
<template><MglMap :accessToken="..." :mapStyle="..." #load="onMapLoaded" /></template>
<script>
methods: {
onMapLoaded(event) {
this.mapboxEvent = Object.freeze({wrapper: event.map});
},
panMap(event) {
this.mapboxEvent.wrapper.panTo([lng, lat], {duration: 1000, zoom: 14});
}
}
</script>
Related
Background
I am using deck.gl's PolygonLayer to render data that looks like this:
data.json:
{
"someKey": "someValue",
"spatialReference": {
"wkid": 23032,
},
"features": [
{
"attributes": {
"polygonName": "MY_POLYGON"
},
"geometry": {
"rings": [
[
[421334, 7240529], ...
],
[
[422656, 7250696], ...
]
]
}
}
]
}
Now, the problem is that decg.gl uses a latitude-longitude coordinate-system, which is different from what this polygon is expressed in.
Deck.GL documentation on rendering layers with different coordinate-systems
So, according to the documentation, deckGL renders each layer separately based on its coordinate system. Therefore, it was important to specify both coordinateOrigin and coordinateSystem props.
Understanding the coordinate system in data.json
So, as far as I understood, the spacialReference value in data.json represents an EPSG code. Using this website, I was able to find a value for the coordinateOrigin prop as [63.510617, 9.210989, 0]. As for the coordinateSystem prop, I used COORDINATE_SYSTEM.METER_OFFSETS. Here's the code:
PolygonLayer.tsx:
import React from "react";
import { COORDINATE_SYSTEM } from "#deck.gl/core/typed";
import { DeckLayer } from "#deck.gl/arcgis";
import { PolygonLayer } from "#deck.gl/layers/typed";
import MapView from "#arcgis/core/views/MapView";
import ArcGISMap from "#arcgis/core/Map";
import "#arcgis/core/assets/esri/themes/light/main.css";
export default function PolygonLayer({layerURL}) {
const mapRef = React.useState(null)
React.useEffect(() => {
fetch(layerURL)
.then(res => res.json())
.then(data => {
const blobURL = new Blob([JSON.stringify(data)], {type: "application/json",});
const url = URL.createObjectURL(blobURL); // this is needed for the layer
const layer = new PolygonLayer({
id: data["features"][0]["attributes"]["polygonName"], // correctly defined
data: url,
filled: true,
getLineWidth: 3,
getLineColor: [255, 255, 255, 0],
getFillColor: [234, 243, 221, 0],
coordinateOrigin: [63.510617, 9.210989, 0], // based on the explanation above
coordinateSystem: COORDINATE_SYSTEM.METER_OFFSETS,
getPolygon: (d) => {
console.log(d); // doesn't log anything
return d.features[0].geometry.rings;
},
});
const deckLayer = new DeckLayer({
"deck.layers": [layer],
});
const arcgisMap = new ArcGISMap({
basemap: "topo-vector",
layers: [deckLayer]
});
new MapView({
container: mapRef?.current,
map: arcgisMap,
center: data["features"][0]["geometry"]["rings"][0][0], // correctly defined
zoom: 9
});
})
.catch(err => console.log(err));
}, [layerURL]);
return <div ref={mapRef} style={{height: "90vh", width: "100%"}}></div>
}
The issue with this code
The problem with this code is that it doesn't render the layer (or the base map) and there's nothing logged in the console for the value of d; as mentioned in the code above.
Making sure the code works
Now, just a sanity check, I have used this url which returns polygons data in the standard LAT LONG format, without using coordinateOrigin or coordinateSystem props as in this example and it worked. So the code is ok rendering LAT LONG system, but breaks when using METERS_OFFSET as in the code provided.
Therefore
Have I figured out the coordinateOrigin correctly? And how can I use this (or another type of) layer to render this data correctly? Any help is appreciated and apologies for the long question!
I am using Chart.js 3.5 and Vue 3.
I was successfully able to draw a chart, and I am trying to trigger a data change, inside a Vue method. Unfortunately, I encounter the following issue: "Uncaught TypeError: Cannot set property 'fullSize' of undefined".
Edit2: Added a missed }. Code should now be runnable
MyChart.vue:
<template>
<canvas id="chartEl" width="400" height="400" ref="chartEl"></canvas>
<button #click="addData">Update Chart</button>
</template>
<script>
import Chart from 'chart.js/auto';
export default {
name: "Raw",
data() {
return {
chart: null
}
},
methods: {
createChart() {
this.chart= new Chart(this.$refs["chartEl"], {
type: 'doughnut',
data: {
labels: ['VueJs', 'EmberJs', 'ReactJs', 'AngularJs'],
datasets: [
{
backgroundColor: [
'#41B883',
'#E46651',
'#00D8FF',
'#DD1B16'
],
data: [100, 20, 80, 20]
}
]
},
options: {
plugins: {}
}
})
},
addData() {
const data = this.chart.data;
if (data.datasets.length > 0) {
data.labels.push('data #' + (data.labels.length + 1));
for (var index = 0; index < data.datasets.length; ++index) {
data.datasets[index].data.push(123);
}
// Edit2: added missed }
this.chart.update(); } // this line seems to cause the error}
}
},
mounted () {
this.createChart()
},
}
</script>
Edit1: Adding the following to the options makes the chart update successfully, but the error is still present and the animation does not work. The chart flickers and displays the final (updated) state. Other animations, such as hiding/showing arcs do not seem to be afected
options: {
responsive: true,
}
Edit3: Adding "maintainAspectRatio:false" option seems to again stop chart from updating (the above mentioned error is still present)
By walking through the debugger, the following function from 'chart.esm.js' seems to be called successfully a few times, and then error out on last call:
beforeUpdate(chart, _args, options) {
const title = map.get(chart); // this returns null, which will cause the next call to error with the above mentioned exception.
layouts.configure(chart, title, options);
title.options = options;
},
//////////////////////
configure(chart, item, options) {
item.fullSize = options.fullSize;
item.position = options.position;
item.weight = options.weight;
},
This may be a stale post but I just spent several hours wrestling with what seems like the same problem. Perhaps this will help you and/or future people with this issue:
Before assigning the Chart object as an attribute of your Vue component, call Object.seal(...) on it.
Eg:
const chartObj = new Chart(...);
Object.seal(chartObj);
this.chart = chartObj;
This is what worked for me. Vue aggressively mutates attributes of objects under its purview to add reactivity, and as near as I can tell, this prevents the internals of Chart from recognising those objects to retrieve their configurations from its internal mapping when needed. Object.seal prevents this by barring the object from having any new attributes added to it. I'm counting on Chart having added all the attributes it needs at init time - if I notice any weird behaviour from this I'll update this post.
1 year later, Alan's answer helps me too, but my code failed when calling chart.destroy().
So I searched and found what seems to be the "vue way" of handling it: markRaw, here is an example using options API:
import { markRaw } from 'vue'
// ...
export default {
// ...
beforeUnmount () {
if (this.chart) {
this.chart.destroy()
}
},
methods: {
createChart() {
const chart = new Chart(this.$refs["chartEl"], {
// ... your chart data and options
})
this.chart = markRaw(chart)
},
addData() {
// ... your update
this.chart.update()
},
},
}
I'm building an angular application using openlayers that when I click a button it will recenter my map .I'm trying to re-center my map when I onClick to a button but it doesnt work.
ERROR TypeError: Cannot read property 'setCenter' of undefined.
Can someone tell me what I'm doing wrong. Thanks in advance !
import { Component } from '#angular/core';
import {fromLonLat} from 'ol/proj'
import {view} from 'ol/View';
import * as ol from 'openlayers';
export class AppComponent {
distance = 60;
points: Array<{ x: number; y: number; }> = [];
position : Array<{ x: number; y: number; id: string; radius: number,color:string, place:string}> =
[
{x:11.5820,y:48.1351,id:"munich",radius:20, color:"red", place:"m"},
{x:13.388866,y:52.517071,id:"berlin", radius:40,color:"blue", place:"b"},
];
coords = {
berlin: [13.388866, 52.517071]
};
onClick (city: string) {
view.setCenter({
center: fromLonLat(this.coords[city]),
duration: 2000
});
}
mapOnClick(evt) {
console.log(evt);
const map = evt.map;
// this bit checks if user clicked on a feature
const p = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
console.log("got feature" + feature.getId());
return feature;
});
}
}
<button id='berlin' (click)="onClick('berlin')">Zoom to Berlin</button>
If you are trying to recenter there must already be a view, but if it was constructed inside the map constructor there won't be a view variable and you will need to reference it using map.getView(). Also setCenter() doesn't do animated recentering. Assuming your map variable is map try:
map.getView().animate({
center: fromLonLat(this.coords[city]),
duration: 2000
})
Lets try this once just for suggestion,
import OlView from 'ol/View';
view: OlView;
ngOnInit() {
this.view = new OlView({
center: fromLonLat(this.coords[city]),
zoom: 3
});
}
I hope its solve your problem if you received proper data for this.coords[city] variable. You need to pass data like this, center: fromLonLat([6.661594, 10.32371]).
For more Reference,
Use OpenLayers 4 with Angular 5
You may get some idea from this above url example.
Thanks,
Muthukumar
I'm building an Ionic application with Native Google Maps and Firebase. I want to load multiple markers on a map, and the positions of these markers (latitude and longitude) are in this Firebase structure:
So I created a provider and a function getPins() to get these positions:
import { ... };
#Injectable()
public arredoresRef:firebase.database.Reference;
export class ArredoresProvider {
constructor() {
this.arredoresRef = firebase.database().ref('/local')
}
getPins(): firebase.database.Reference {
return this.arredoresRef.child('/local');
}
}
And I'm trying to put these positions in an array:
import { ... };
#IonicPage({ ... })
#Component({ ... })
export class ArredoresPage {
constructor( ... ) { ... }
ionViewDidEnter() {
this.arredoresProvider.getPins().on('value', snapshot => {
this.pins = [];
snapshot.forEach( snap => {
this.pins.push({
latitude: snap.val().latitudeLocal,
longitude: snap.val().longitudeLocal
});
return false
});
});
}
}
But it's not working! It's my first time working with Firebase and Ionic, so I'm confused about how Firebase read data.
This text was really useful to me, but it does not use Firebase data.
Finally, I apologize for my bad english!
I have implemented the first solution to this:
Get data from Firebase in Ionic 2
Essentially, you have to use the list reference and make sure you call it using the options {enableSnapshot: true}. Moreover, your data in the structure does not have a .latitudeLocal property on it. Instead, you have to go further in the data structure to access these, for example, you could use another .forEach statement.
I created the following setup
HTML
<div class="col-md-6">
<div id="GISMap" v-el:map></div>
</div>
main.js VUE
var Vue = require('vue');
import VueResource from 'vue-resource';
import HomeView from './components/HomeView.vue';
Vue.use(VueResource);
Vue.config.debug = true;
window.app = new Vue({
el: '.content',
components: {
HomeView
},
methods: {
// Broadcast info that API has been loaded. Listen to this in GoogleMaps Module
init: function() {
this.$broadcast('MapsApiLoaded');
}
}
})
MODULE 1: HomeView.vue
<script>
export default {
events: {
MapsApiLoaded: function() {
// Initialize GIS Map
initGISMap(this.$els.map);
}
}
}
</script>
GoogleMaps.js
function initGISMap(selector) {
map = new google.maps.Map(selector, {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
// Set initial Location and center map to this location
initialLocation = new google.maps.LatLng(48.184845, 11.252553);
map.setCenter(initialLocation);
// Create a searchmarker
searchMarker = createMarker();
// Init Autocomplete for GIS
initAutoComplete();
}
I want to create the map in the div container with the tag v-el:map. When I call initGISMap(this.$els.map) within the module, and print out the value in the console, it is empty. So it seems that I don't have access to this element from within a module? How do I need to change this?
Overall approach:
main.js init() method is broadcasting an info when the map is loaded. This is caught within the HomeView module and the initGISMap is supposed to be called, residing in the GoogleMaps.js. This is all working fine, but the element to be handed over is missing.
The element is probably not in the scope of your HomeView module.
The good thing is: vm.$broadcast() can take more than one argument, so you can pass the element directly to the function with
this.$broadcast('MapsApiLoaded', this.$els.map);
and in HomeView.vue, you can pass it on with
export default {
events: {
MapsApiLoaded: initGISMap;
}
}
(You don't have to wrap initGISMap in a closure here.)