Adding markerclustergroup to leaflet overlay does not update in Vue.js app - vue.js

I have an overlay control on my leaflet map in a vue.js application. It contains two layers. The ILZipCodes layer renders perfectly. However, the "markers" layer does not appear when I select the checkbox in the layer control. Why is this? I reckon I may be setting up the layer control and populating the clusters in the wrong sequence.
Cheers
<template>
<div>
<div class="mx-auto my-6 loader" v-if="isSearching"></div>
<div class="tooManyResultsError" v-if="tooManyResults">
Your search brought back too many results to display. Please zoom in or refine your search with the text box and
filters.
</div>
<div id="leafletMapId"></div>
</div>
</template>
<script>
//The center coordinate and zoom level that the map should initialize to
// to capture all of the continental United States
const INITIAL_CENTER_LATITUDE = 34;
const INITIAL_CENTER_LONGITUDE = -96;
const INITIAL_ZOOM = 4;
/* Leaflet performs slowly with reactivity ("observable" data object variables).
* To work around this, I removed myMap and markers from the data object.
*/
/* If the user zooms out or pans beyond the boundaries of the previous fetch's dataset, then
* the client fetches location data from the server to replace the previous map data. If the user
* zooms or pans but stays within the boundaries of the dataset currently displayed on the map, then
* the client does not run another fetch.
* */
import axios from "axios";
import store from "../store.js";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet.markercluster/dist/MarkerCluster.css";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";
import "leaflet.markercluster/dist/leaflet.markercluster-src.js";
import "leaflet-ajax/dist/leaflet.ajax.js";
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";
export default {
name: "ContactsMap",
mounted() {
this.fetchAggregatedDistrictStats();
},
methods: {
async fetchAggregatedDistrictStats() {
axios.get(... // fetches some statistics for the other overlay layers
);
},
createMapWithLeafletAndMapTiler() {
var $this = this;
var streetTilesLayer = L.tileLayer(MAPTILER_STREETS_URL, {
maxZoom: 18,
minZoom: 2,
attribution: MAPBOX_ATTRIBUTION,
tileSize: 512,
zoomOffset: -1
});
// eslint-disable-next-line
var satelliteTilesLayer = L.tileLayer(MAPTILER_SATELLITE_URL, {
maxZoom: 18,
minZoom: 2,
tileSize: 512,
zoomOffset: -1
});
var baseMaps = {
Satellite: satelliteTilesLayer,
Streets: streetTilesLayer
};
if (myMap != undefined) {
myMap.remove();
}
var myMap = L.map("leafletMapId", {
layers: [streetTilesLayer],
}).setView(this.center, this.zoom);
var markers = L.markerClusterGroup({
iconCreateFunction: function(cluster) {
var count = cluster.getChildCount();
var digits = (count + "").length;
return L.divIcon({
html: "<b>" + count + "</b>" + digits,
className: "cluster digits-" + digits,
iconSize: 22 + 10 * digits
});
}
});
async function fetchLocations(shouldProgrammaticallyFitBounds) {
markers.clearLayers();
markers = L.markerClusterGroup({
chunkedLoading: true,
iconCreateFunction: function(cluster) {
var count = cluster.getChildCount();
var digits = (count + "").length;
return L.divIcon({
html: "<b>" + count + "</b>",
className: "cluster digits-" + digits,
iconSize: 22 + 10 * digits
});
}
});
axios
.get("/maps/" + $this.list.list_id, {
//fetches markerclusters
})
.then(
response => {
$this.tooManyResults = false;
var addressPoints = response.data.recordsList;
for (var i = 0; i < addressPoints.length; i++) {
var a = addressPoints[i];
var title = a[2];
var marker = L.marker(L.latLng(a[0], a[1]));
marker.bindPopup(title);
markers.addLayer(marker); // This is where I'm adding the markers and markerclusters to the layer titled "markers"
// myMap.addLayer(markers); //If I uncomment this, then the markers layer is always on the map, i.e. not as an overlay layer
}
},
error => {
$this.isSearching = false;
document.getElementById("leafletMapId").style.display = "block";
store.setErrorMessage("Network error searching list", error);
}
);
}
myMap.on("zoomend", handlerFunction);
myMap.on("dragend", handlerFunction);
var defaultPolygonStyle = {
color: "black",
weight: 1,
opacity: 0.8,
fillOpacity: 0.1
};
var NationalCongressional = new L.geoJson.ajax(
"http://localhost:8080/assets/geo/NationalCongressional.json",
{
style: defaultPolygonStyle,
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.NAMELSAD);
if (feature.properties.NAMELSAD == "Congressional District 8") {
layer.setStyle({ color: "orange" });
}
}
}
);
function getColorFromRedBlueRange(d) {
return d > 0.8
? "#FF0000"
: d > 0.7
? "#FF006F"
: d > 0.55
? "#FF00EF"
: d > 0.45
? "#DE00FF"
: d > 0.3
? "#BC00FF"
: d > 0.2
? "#6600FF"
: "#00009FF";
}
var ILZipCodes = new L.geoJson.ajax(
"https://raw.githubusercontent.com/OpenDataDE/State-zip-code-GeoJSON/master/il_illinois_zip_codes_geo.min.json",
{
// style: defaultPolygonStyle,
onEachFeature: function(feature, layer) {
layer.bindPopup(
feature.properties.ZCTA5CE10 +
", " +
$this.zipData[feature.properties.ZCTA5CE10]
);
layer.setStyle({
color: getColorFromRedBlueRange(
$this.zipData[feature.properties.ZCTA5CE10]
),
weight: 0,
fillOpacity: 0.3
});
}
}
);
var overlays = {
Voters: voterGroup,
ILZipCodes: ILZipCodes,
};
L.control.layers(baseMaps, overlays).addTo(myMap);
fetchLocations(true);
}
}
};

You add voterGroup to your Layers Control, instead of your markers.
Then simply do not re-assign a MarkerClusterGroup into your markers variable (after you use clearLayers) and you should be fine.

Related

ArcGIS map polygon store in ArcGIS

I have to store the created polygon in ArcGIS. Once the polygon is stored in ArcGIS, it returns an ID (Object ID). With the object ID, the administrator can access the polygon in ArcGIS. I found a piece of code in one of our old systems the code is written in version 3xx.
function SendFeaturesToParent()
{
editingEnabled = false;
editToolbar.deactivate();
lyrMeters.clearSelection();
polygon = currentEVT.graphic.geometry;
var query = new Query();
query.geometry = polygon;
lyrAreas.applyEdits(null, [currentEVT.graphic], null);
var attributes = [];
var featureValues = [];
for (var x = 0; x < selectedfeatures.length; x++) {
featureValues.push("METER_ID: " + selectedfeatures[x].attributes["METER_ID"] + ", Type: " + selectedfeatures[x].attributes["Type"]);
attributes.push(selectedfeatures[x].attributes);
}
console.log("attributes"+ attributes);
//Send the array of meter values back to the parent page.
var objectId = lyrAreas._defnExpr;
objectId = objectId.split('=');
window.parent.postMessage(
{
event_id: 'my_cors_message',
data: attributes,
objectId: objectId[1]
},
"*" //or "www.parentpage.com"
);
$('#modelConfirm').modal('hide');
}
I need to implement in latest version of arcGIS API 4.23. What are the applyEdits do?
/**** modified code in 4.23 */
var token = '';
const PermitAreaURL = "url_1";
const locatorUrl = "url_2";
const streetmapURL = "url_3";
const streetmapLebelsURL = "url_4";
const MetersURL = "url_5";
const MetersWholeURL = "url_6";
require(["esri/config",
"esri/Map",
"esri/views/MapView",
"esri/layers/FeatureLayer",
"esri/layers/TileLayer",
"esri/layers/VectorTileLayer",
"esri/layers/GraphicsLayer",
"esri/widgets/Search",
"esri/widgets/Sketch/SketchViewModel",
"esri/geometry/geometryEngineAsync",
],
function (esriConfig, Map, MapView, FeatureLayer, TileLayer, VectorTileLayer, GraphicsLayer, Search, SketchViewModel, geometryEngineAsync) {
esriConfig.apiKey = "AAPK3f43082c24ae493196786c8b424e9f43HJcMvP1NYaqIN4p63qJnCswIPsyHq8TQHlNtMRLWokqJIWYIJjga9wIEzpy49c9v";
const graphicsLayer = new GraphicsLayer();
const streetmapTMLayer = new TileLayer({
url: streetmapURL
});
const streetmapLTMLayer = new VectorTileLayer({
url: streetmapLebelsURL
});
const lyrwholeMeters = new FeatureLayer({
url: MetersWholeURL,
outFields: ["*"],
});
const lyrMeters = new FeatureLayer({
url: MetersURL,
outFields: ["*"],
});
// const permitAreaUrl = new FeatureLayer({
// url: PermitAreaURL,
// outFields: ["*"],
// });
// console.log(lyrMeters);
const map = new Map({
basemap: "arcgis-topographic", // Basemap layer service
layers: [streetmapTMLayer, streetmapLTMLayer, lyrMeters, lyrwholeMeters, graphicsLayer]
});
const view = new MapView({
map: map,
center: [-95.9406, 41.26],
zoom: 16,
maxZoom: 21,
minZoom: 13,
container: "viewDiv" // Div element
});
view.when(() => {
const polygonSymbol = {
type: "simple-fill", // autocasts as new SimpleFillSymbol()
color: [207, 34, 171, 0.5],
outline: {
// autocasts as new SimpleLineSymbol()
color: [247, 34, 101, 0.9],
}
};
const sketchViewModel = new SketchViewModel({
view: view,
layer: graphicsLayer,
polygonSymbol: polygonSymbol,
});
sketchViewModel.create("polygon", { mode: "hybrid" });
// Once user is done drawing a rectangle on the map
// use the rectangle to select features on the map and table
sketchViewModel.on("create", async (event) => {
if (event.state === "complete") {
// this polygon will be used to query features that intersect it
const geometries = graphicsLayer.graphics.map(function (graphic) {
return graphic.geometry
});
const queryGeometry = await geometryEngineAsync.union(geometries.toArray());
selectFeatures(queryGeometry);
}
});
});
// This function is called when user completes drawing a rectangle
// on the map. Use the rectangle to select features in the layer and table
function selectFeatures(geometry) {
console.log(geometry.rings);
// create a query and set its geometry parameter to the
// rectangle that was drawn on the view
const query = {
geometry: geometry,
outFields: ["*"]
};
lyrwholeMeters.queryFeatures(query).then(function (results) {
var lyr = results.features;
console.log(lyr);
// save the polygon
lyr.applyEdits({
addFeatures: [geometry] /*updates*/
});
lyr.forEach(element => {
console.log(`MeterID-${element.attributes.METER_ID}, OBJECTID-${element.attributes.OBJECTID}, Passport_ID-${element.attributes.Passport_ID}`);
});
});
}
// search widget
const searchWidget = new Search({
view: view,
});
view.ui.add(searchWidget, {
position: "top-left",
index: 2
});
});
applyEdits method is the way you to add/update/delete features in a feature layer. Both version of the library have the method although in version 4 takes an object that contain the edits instead of the separated parameters. In your code, version 3, it is,
lyrAreas.applyEdits(null, [currentEVT.graphic], null);
first parameter is for new features, second for updates on features and third for features to delete.
While in version 4 it should be,
lyrAreas.applyEdits({
updateFeatures: [currentEVT.graphic] /*updates*/
});
the object goes all the informations about the edits, in this case you only have updates.
I am not completely sure about this line,
var objectId = lyrAreas._defnExpr;
objectId = objectId.split('=');
I am guessing is the definition expression of the feature layer, a sql expression, that is why in the next line it is split, to use later the value. Version 3 library did not expose the property but gives set and get methods.
Version 4 have the property and works in similar way. In this case for latest version it should be,
var objectId = lyrAreas.definitionExpression;
objectId = objectId.split('=');
So I do not think you will have
ArcGIS API v3 - FeatureLayer
ArcGIS API v4 - FeatureLayer

How to get value for selected place in particular area when draw polyline or polygon through Javascript ArcGIS Api from TileLayer?

Actually I am using ArcGIS API for JavaScript 4.7 and i have a custom internal layer . I want to get name of place particular area when draw polyline the column name is (PLC_NAME) . How to achieve that ?
Suppose I draw a area through polyline. In this area there are places . Now I need to get name of these places .
you can find the using code in below i am using the TileLayer.
require([
"esri/views/MapView",
"esri/Map",
"esri/Basemap",
"esri/layers/TileLayer",
"esri/layers/MapImageLayer",
"esri/widgets/Sketch/SketchViewModel",
"esri/geometry/geometryEngine",
"esri/widgets/CoordinateConversion",
"esri/geometry/support/webMercatorUtils",
"esri/Graphic",
"esri/layers/GraphicsLayer",
"esri/config",
"esri/core/urlUtils",
"esri/widgets/Search",
"esri/tasks/Locator",
"esri/layers/FeatureLayer",
"esri/widgets/Expand",
"dojo/domReady!"
], function (
MapView, Map, Basemap, TileLayer, MapImageLayer,
SketchViewModel,
geometryEngine,
CoordinateConversion,
webMercatorUtils,
Graphic, GraphicsLayer, esriConfig, urlUtils,Search,Locator,FeatureLayer,Expand
) {
esriConfig.request.proxyUrl = "xxxxxxxxxxxxxxx";
urlUtils.addProxyRule({
urlPrefix: "xxxxxxxxxxxxxxxxxxx",
proxyUrl: "xxxxxxxxxxxxxxxxxx"
});
var tempGraphicsLayer = new GraphicsLayer();
var saveGraphicsLayer = new GraphicsLayer();
var updateGraphic;
let highlight = null;
'xxxxxxxxxxxxxxxxxxxxxxxxx';
var myMap;
var layer = new TileLayer({
url: mapUrl
});
var towerLayer = new MapImageLayer({
url: 'xxxxxxxxxxxxxxxxxxxxxxx'
});
myMap = new Map({
layers: [layer, tempGraphicsLayer, saveGraphicsLayer]
});
myMap.add(towerLayer);
view = new MapView({
center: [-55.1683665, 39.951817],
container: "viewDiv",
map: myMap,
zoom: 14
});
var ccWidget = new CoordinateConversion({
view: view
});
// Adds the search widget below other elements in
// the top left corner of the view
view.ui.add(searchWidget, {
position: "top-right",
index: 1
});
view.ui.add(ccWidget, "bottom-left");
view.ui.add("topbar", "top-right");
var pointSymbol = { // symbol used for points
type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
style: "square",
color: "#8A2BE2",
size: "16px",
outline: { // autocasts as new SimpleLineSymbol()
color: [255, 255, 255],
width: 3 // points
}
}
var polylineSymbol = { // symbol used for polylines
type: "simple-line", // autocasts as new SimpleLineSymbol()
color: "#8A2BE2",
width: "4",
style: "dash"
}
var polygonSymbol = { // symbol used for polygons
type: "simple-fill", // autocasts as new SimpleFillSymbol()
color: "rgba(138,43,226, 0.8)",
style: "solid",
outline: {
color: "white",
width: 1
}
}
var polygonBoundrySymbol = { // symbol used for polygons
type: "simple-line", // autocasts as new SimpleFillSymbol()
color: "red"
}
// ################## U R HERE ################## ################## U R HERE ##################
################## U R HERE ##################
let drawBoundry = function(){
//let boundryJson = '&G_GEO_LIMITS.';
let boundryJson = $v('P0_USER_LIMITS');
if(boundryJson){
// let boundry = Graphic.fromJSON(JSON.parse('&G_GEO_LIMITS.'));
let boundry = Graphic.fromJSON(JSON.parse(boundryJson));
boundry.symbol = polygonBoundrySymbol;
tempGraphicsLayer.add(boundry);
return boundry;
}
}
/*
let boundry = drawBoundry();
*/
view.when(function () {
$('.esri-view-root').on('click', '.esri-print__export-button', function(e){
//console.log('event bubbling', e);
//console.log('event bubbling this', this);
e.preventDefault();
saveExportedImg();
});
// create a new sketch view model
var sketchViewModel = new SketchViewModel({
view: view,
layer: tempGraphicsLayer,
pointSymbol: pointSymbol,
polylineSymbol: polylineSymbol,
polygonSymbol: polygonSymbol
});
//setUpClickHandler();
// ************************************************************
// Get the completed graphic from the event and add it to view.
// This event fires when user presses
// * "C" key to finish sketching point, polygon or polyline.
// * Double-clicks to finish sketching polyline or polygon.
// * Clicks to finish sketching a point geometry.
// ***********************************************************
sketchViewModel.on("draw-complete", addGraphic);
sketchViewModel.on("update-complete", addGraphic);
sketchViewModel.on("update-cancel", addGraphic);
sketchViewModel.on("vertex-add", addGraphic);
function addGraphic(evt) {
// console.log ('graphic.geometry',evt.geometry)
//let currentGraphic = popActiveGraphic(tempGraphicsLayer);
let currentGraphic = saveGraphicsLayer.graphics.items.pop();
var geometry = evt.geometry;
var vertices = evt.vertices;
var symbol;
var attr = {
Name: "Selected Area",
X: $v('P24_X'),
Y: $v('P24_Y')
};
// Choose a valid symbol based on return geometry
switch (geometry.type) {
case "point":
symbol = pointSymbol;
break;
case "polyline":
symbol = polylineSymbol;
break;
default:
symbol = polygonSymbol;
break;
}
// Create a new graphic; add it to the GraphicsLayer
// console.log("b4 graphic");
geometry = webMercatorUtils.webMercatorToGeographic(geometry)
/*if(boundry){
var contains = geometryEngine.contains(boundry.geometry, geometry);
var within = geometryEngine.within(geometry, boundry.geometry);
} else {*/
var within = true;
//}
if(within){
let graphic = new Graphic({
geometry: geometry,
symbol: symbol,
//attributes: attr,
popupTemplate: {
title: "{Name}",
content: [{
type: "fields",
fieldInfos: [{
fieldName: "X"
}, {
fieldName: "Y"
}]
}]
}
});
tempGraphicsLayer.add(graphic);
if(currentGraphic){
//currentGraphic.geometry.rings.push(geometry.rings[0]);
geometry.rings.forEach( ring => currentGraphic.geometry.addRing(ring));
//currentGraphic.geometry.addRing(geometry.rings);
//console.log('current active', geometry);
// console.log('current graphic', currentGraphic.geometry);
graphic = currentGraphic;
}
var saveObj = graphic.toJSON();
// console.log('saveObj', saveObj);
$x('P24_JSON').value = JSON.stringify(saveObj);
} else {
apex.message.alert('&G_MAP_BOUNDRY_MSG.');
}
updateGraphic = null;
}
function addMultiGraph(evt1) {
//let currentGraphic = popActiveGraphic(tempGraphicsLayer);
let currentGraphic = saveGraphicsLayer.graphics.items.pop();
var geometry = evt1.geometry;
var vertices = evt1.vertices;
var symbol;
// Choose a valid symbol based on return geometry
switch (geometry.type) {
case "point":
symbol = pointSymbol;
break;
case "polyline":
symbol = polylineSymbol;
break;
default:
symbol = polygonSymbol;
break;
}
//console.log("ring",geometry.rings )
let graphic = new Graphic({
geometry: geometry,
symbol: symbol,
//attributes: attr,
popupTemplate: {
title: "{Name}",
content: [{
type: "fields",
fieldInfos: [{
fieldName: "X"
}, {
fieldName: "Y"
}]
}]
}
});
tempGraphicsLayer.add(graphic);
if(currentGraphic){
geometry.rings.forEach( ring => currentGraphic.geometry.addRing(ring));
}
var saveObj1 = graphic.toJSON();
//console.log('saveObj', graphic);
$x('P24_JSON').value = JSON.stringify(saveObj1);
updateGraphic = null;
}
window.loadGraphic = function(polygon){
if(polygon===undefined || polygon === ''){
console.error('no polygon');
} else {
var graphic = Graphic.fromJSON(JSON.parse(polygon));
if (graphic.geometry){
addMultiGraph(graphic);
//*********************************************************************
view.center.longitude = graphic.geometry.centroid.longitude;
view.center.latitude = graphic.geometry.centroid.latitude;
view.center = [graphic.geometry.centroid.longitude,
graphic.geometry.centroid.latitude];
view.zoom = 12;
}
}
}
// *************************************
// activate the sketch to create a point
// *************************************
var drawPointButton = document.getElementById("pointButton");
drawPointButton.onclick = function () {
// set the sketch to create a point geometry
sketchViewModel.create("point");
setActiveButton(this);
};
// ****************************************
// activate the sketch to create a polyline
// ****************************************
var drawLineButton = document.getElementById("polylineButton");
drawLineButton.onclick = function () {
// set the sketch to create a polyline geometry
sketchViewModel.create("polyline");
setActiveButton(this);
};
var drawPolygonButton = document.getElementById("polygonButton");
drawPolygonButton.onclick = function () {
// set the sketch to create a polygon geometry
sketchViewModel.create("polygon");
setActiveButton(this);
};
// ***************************************
// activate the sketch to create a rectangle
// ***************************************
var drawRectangleButton = document.getElementById(
"rectangleButton");
drawRectangleButton.onclick = function () {
// set the sketch to create a polygon geometry
sketchViewModel.create("rectangle");
setActiveButton(this);
};
document.getElementById("resetBtn").onclick = function () {
sketchViewModel.reset();
tempGraphicsLayer.removeAll();
saveGraphicsLayer.removeAll();
setActiveButton();
drawBoundry();
};
function setActiveButton(selectedButton) {
// focus the view to activate keyboard shortcuts for sketching
view.focus();
var elements = document.getElementsByClassName("active");
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove("active");
}
if (selectedButton) {
selectedButton.classList.add("active");
}
}
// ************************************************************************************
// set up logic to handle geometry update and reflect the update on "tempGraphicsLayer"
// ************************************************************************************
function setUpClickHandler() {
view.on("click", function (evt) {
view.hitTest(evt).then(function (response) {
var results = response.results;
// Found a valid graphic
if (results.length && results[results.length - 1]
.graphic) {
// Check if we're already editing a graphic
if (!updateGraphic) {
// Save a reference to the graphic we intend to update
updateGraphic = results[results.length - 1].graphic;
// Remove the graphic from the GraphicsLayer
// Sketch will handle displaying the graphic while being updated
tempGraphicsLayer.remove(updateGraphic);
sketchViewModel.update(updateGraphic.geometry);
}
}
});
});
}
function errorCallback(error) {
console.log('error:', error);
}
// ************************************************************************************
// returns graphic object if drawn on the map to contcat new graphics to it
// ************************************************************************************
function popActiveGraphic(graphicsLayer){
let length = graphicsLayer.graphics.length;
let count = 0;
if($v('P0_USER_LIMITS').length > 0){
count++;
}
if(length > count){ //active drawing detected
let result = graphicsLayer.graphics.items[length-1];
graphicsLayer.remove(result);
return result;
}
}
});
});
OK, you can resolve the queries on the client or on the server. Depends on your task what options you can pick on.
If you are going to use a spatial query, like the one you mention, and you will apply it on a FeatureLayer, you could solve it on the client. This is a good solution because you already have the features, you are seeing them. Here you have a question whis this situation, how-to-get-get-name-of-hospital-or-street-in-particular-area-when-draw-polyline.
Now, If you need to query something that might not be in your extent (you don't have the features) or you are not using a FeatureLayer, you probably will need to command the server to do this. But don't worry the library has several tools to work with, like QueryTask.
Here you have the same example of the answer link before but using QueryTask.
<html>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='initial-scale=1, maximum-scale=1, user-scalable=no'>
<title>Select Feature With Polygon</title>
<style>
html,
body {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
#viewDiv {
padding: 0;
margin: 0;
height: 400px;
width: 100%;
}
#namesDiv {
margin: 10px;
height: 200px;
width: 100%;
font-style: italic;
font-weight: bold;
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
color: green;
overflow: auto;
}
</style>
<link rel='stylesheet' href='https://js.arcgis.com/4.15/esri/css/main.css'>
<script src='https://js.arcgis.com/4.15/'></script>
<script>
require([
'esri/Map',
'esri/views/MapView',
'esri/layers/MapImageLayer',
'esri/layers/GraphicsLayer',
'esri/widgets/Sketch/SketchViewModel',
'esri/Graphic',
'esri/widgets/Expand',
'esri/tasks/QueryTask',
'esri/tasks/support/Query'
], function (
Map,
MapView,
MapImageLayer,
GraphicsLayer,
SketchViewModel,
Graphic,
Expand,
QueryTask,
Query
) {
let highlight = null;
const states = new MapImageLayer({
url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer'
});
const queryTask = new QueryTask({
url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/2'
});
const polygonGraphicsLayer = new GraphicsLayer();
const selected = new GraphicsLayer();
const map = new Map({
basemap: 'streets',
layers: [states, polygonGraphicsLayer, selected]
});
const view = new MapView({
container: 'viewDiv',
map: map,
center: [-75.1683665, 39.951817],
zoom: 8
});
const sketchViewModel = new SketchViewModel({
view: view,
layer: polygonGraphicsLayer,
pointSymbol: {
type: 'simple-marker',
color: [255, 255, 255, 0],
size: '1px',
outline: {
color: 'gray',
width: 0
}
}
});
sketchViewModel.on('create', function (event) {
if (event.state === 'complete') {
polygonGraphicsLayer.remove(event.graphic);
selectFeatures(event.graphic.geometry);
}
});
const namesDiv = document.getElementById('namesDiv');
view.ui.add('select-by-polygon', 'top-left');
const selectButton = document.getElementById('select-by-polygon');
selectButton.addEventListener('click', function () {
clearUpSelection();
sketchViewModel.create('polygon');
});
function selectFeatures(geometry) {
selected.removeAll();
const query = new Query();
query.returnGeometry = true;
query.outFields = ['*'];
query.geometry = geometry;
queryTask
.execute(query)
.then(function (results) {
const graphics = results.features.map(r => {
r.symbol = {
type: 'simple-fill',
fill: 'none',
outline: {
color: 'cyan',
width: 2
}
};
return r;
});
selected.addMany(graphics);
namesDiv.innerHTML = graphics.map(g => g.attributes.NAME).join(',');
})
.catch(errorCallback);
}
function clearUpSelection() {
selected.removeAll();
namesDiv.innerHTML = null;
}
function errorCallback(error) {
console.log('error:', error);
}
});
</script>
</head>
<body>
<div id='viewDiv'>
<div
id="select-by-polygon"
class="esri-widget esri-widget--button esri-widget esri-interactive"
title="Select counties by polygon"
>
<span class="esri-icon-checkbox-unchecked"></span>
</div>
</div>
<div id="namesDiv"></div>
</body>
</html>
To close I leave you this link to the documentation that explains very well all the possibilities, pros and cons.

how to re initialize webglglobe with vue

I am using http://www.webglearth.org/api for a globe on my vue app.
I have a route called globe that initializes the globe with new WE.map. when I change routes and go back it re initializes but re adds scripts to my head which jam up the globe tiles from loading. Is there a way to keep and re use an instantiated object? Or any tips that could help with this
I tried saving my created globe in the store and re using it though it wont reload without doing a WE.map and that method adds the headers
this method is being called on vue create
initialize(data) {
var earth = WE.map("earth_div");
WE.tileLayer(
"https://webglearth.github.io/webglearth2-offline/{z}/{x}/{y}.jpg",
{
tileSize: 256,
bounds: [[-85, -180], [85, 180]],
minZoom: 0,
maxZoom: 16,
attribution: "WebGLEarth example",
tms: true
}
).addTo(earth);
data.forEach(doc => {
let latlng = [];
console.log(typeof doc.data().images);
console.log(doc.data().galleryTitle);
latlng[0] = doc.data().lat;
latlng[1] = doc.data().lng;
console.log(latlng);
var marker = WE.marker(latlng).addTo(earth);
marker.element.id = doc.data().safeTitle;
let popup = `${doc.data().location}`;
marker
.bindPopup(popup, { maxWidth: 150, closeButton: true })
.openPopup();
marker.element.onclick = e => {
console.log(e.target.parentElement.id);
var gallery = e.target.parentElement.id;
this.$router.push({ path: "/gallery/" + gallery });
};
});
// Start a simple rotation animation
var before = null;
requestAnimationFrame(function animate(now) {
console.log('animating')
var c = earth.getPosition();
var elapsed = before ? now - before : 0;
before = now;
earth.setCenter([c[0], c[1] + 0.1 * (elapsed / 30)]);
// requestAnimationFrame(animate);
});
earth.setView([46.8011, 8.2266], 3);
this.$store.commit('setEarth',earth)
},
I would like the globe to re initiate without re adding headers.

data is shown on chartjs-vue only after resizing browser or opening developer tools

im having hard time fixing this problem.
i get my data with a get request, after opening developer tools or resizing browser the data is shown.
i have tried some delay or timeout solutions but sadly could not make it work. i need the fastest solution, even if it is a "dirty hack" sort of solution.
im using vue 2.9.1 and chartjs-vue 2.7.1.
thank you!
this is my code:
import {Line} from 'vue-chartjs'
export default {
name: 'Events',
extends: Line,
created: function () {
this.getEvents();
},
data () {
return {
gradient: null,
gradient2: null,
datesList : [],
avgList: []
}
},
methods:{
graphClickEvent(event, array){
var points = this.getElementAtEvent(event)
},
getEvents () {
this.$http.get('http://localhost:8081/users/getAllEvents'
,{headers: {'Content-Type': 'application/json',
'Authorization': localStorage.getItem('token'),}
}).then((res) => {
// res.body = array of event object
var eventsArr = res.body;
var arrayLength = eventsArr.length;
for (var i = 0; i < arrayLength; i++) {
var date = new Date(parseInt(eventsArr[i].startTime))
var day = date.getDate()
var month = date.getMonth()
var year = date.getFullYear()
var hours = date.getHours()
hours = ("0" + hours).slice(-2);
var minutes = date.getMinutes()
minutes = ("0" + minutes).slice(-2);
var str = day;
var str = day + "." + (month + 1) + "." + year +" - " + hours + ":" + minutes
this.datesList.push(str);
}
for (var i = 0; i < arrayLength; i++) {
var evnt = eventsArr[i];
this.avgList.push({label: evnt.name,y: evnt.pulseAverage ,tag: evnt.tag, id: evnt.id });
}
})
}
},
mounted () {
this.gradient = this.$refs.canvas.getContext('2d').createLinearGradient(0, 0, 0, 450)
this.gradient2 = this.$refs.canvas.getContext('2d').createLinearGradient(0, 0, 0, 450)
this.gradient.addColorStop(0, 'rgba(255, 0,0, 0.5)')
this.gradient.addColorStop(0.5, 'rgba(255, 0, 0, 0.25)');
this.gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
this.gradient2.addColorStop(0, 'rgba(0, 231, 255, 0.9)')
this.gradient2.addColorStop(0.5, 'rgba(0, 231, 255, 0.35)');
this.gradient2.addColorStop(1, 'rgba(0, 231, 255, 0)');
this.renderChart({
labels: this.datesList,
datasets: [
{
label: 'Events',
borderColor: '#05CBE1',
pointBackgroundColor: 'white',
pointBorderColor: 'white',
borderWidth: 2,
backgroundColor: this.gradient2,
data: this.avgList
},
]
,
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
}
//
,{ onClick: function(event){
var activePoints = this.getElementAtEvent(event)
var firstPoint = activePoints[0];
if(firstPoint !== undefined){
var label = this.data.labels[firstPoint._index];
var value = this.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
var location = "eventGraph?id=" + value.id;
window.location.href = location;
}
}
, responsive: true, maintainAspectRatio: false,fontColor: '#66226',
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
title: function(tooltipItems, data) {
var evnt = data.datasets[0].data[tooltipItems[0].index].label;
return evnt
},
label: function(tooltipItems, data) {
var avg = 'Average heart: ' + [tooltipItems.yLabel];
var evnt = 'Type: ' + data.datasets[0].data[tooltipItems.index].tag;
return [avg,evnt];
}
}
}
})
}
}
It sounds like an initialization issue where the chart is initially rendered in an element that is not visible or it can't determine the size of the parent.
I see similar issues doing a Google:
ChartJS won't draw graph inside bootstrap tab until window resize #17
Charts rendered in hidden DIVs will not display until browser resize #29
Chart.js not rendering properly until window resize or toggling line in legend
One suggested doing a chart refresh when everything is visible:
setTimeout(function() { myChart.update(); },1000);
In think in vue this could be done in the mount function.
I'm sure there is a more elegant way to handle this with a watch function or something similar for instance.
Updated:
As mentioned in the comments, I've seen references to people firing a window resize event manually using:
window.dispatchEvent(new Event('resize'));
I think it would probably work in the mounted function of the vue component:
export default {
name: 'graphs-component',
mounted: function(){
window.dispatchEvent(new Event('resize'));
}
}
You might even wrap it in a setTimeout to ensure everything is loaded.

dojo 1.7 IE9 widget function call not triggering

I'm trying to add a button to a custom pallete to call a function "uiFileInputDlg" which is in the workspace that uses the widget. The upbtn appears on the pallete, but it is not triggering the DoUpload function which is connected in postcreate to then call on "uiFileInputDlg".
works flawlessly in firefox.
we're user dojo 1.7.2
-----------THE TEMPLATE-------------------------
<div class="dijitInline dijitColorPalette">
<div class="dijitColorPaletteInner" data-dojo-attach-point="divNode" role="grid" tabIndex="${tabIndex}">
</div>
<button type="button" id="upbtn"
data-dojo-type="dijit.form.Button"
data-dojo-props="id:'upbtn'"
data-dojo-attach-point="btnUpNode">
Upload New Image
</button>
</div>
-------------------------THE WIDGET--------------------------
//dojo.provide("meemli.UploadPalette");
define([ 'dojo/_base/declare',
'dijit/_WidgetBase',
'dijit/_TemplatedMixin',
'dojo/i18n!dijit/nls/common',
'dojo/text!./templates/UploadPalette.html',
'dijit/_WidgetsInTemplateMixin',
'dojo/_base/lang'
],
function(declare, w, t, i18n, template, witm, lang){
console.log('meemli.UploadPalette: Requiring dijit/nls/common.js INSTEAD OF dojo/nls/common' + i18n.invalidMessage);
return declare("meemli.UploadPalette",
[dijit._Widget, dijit._Templated],
{
// summary: A keyboard accessible color-picking widget
// description:
// Grid showing various colors, so the user can pick a certain color
// Can be used standalone, or as a popup.
//
// example:
// | <div dojoType="dijit.ColorPalette"></div>
//
// example:
// | var picker = new dijit.ColorPalette({ },srcNode);
// | picker.startup();
//
// defaultTimeout: Number
// number of milliseconds before a held key or button becomes typematic
defaultTimeout: 500,
// timeoutChangeRate: Number
// fraction of time used to change the typematic timer between events
// 1.0 means that each typematic event fires at defaultTimeout intervals
// < 1.0 means that each typematic event fires at an increasing faster rate
timeoutChangeRate: 0.90,
// palette: String
// Size of grid, either "7x10" or "3x4".
palette: "3x3",
//_value: String
// The value of the selected color.
value: null,
//_currentFocus: Integer
// Index of the currently focused color.
_currentFocus: 0,
// _xDim: Integer
// This is the number of colors horizontally across.
_xDim: null,
// _yDim: Integer
/// This is the number of colors vertically down.
_yDim: null,
// _palettes: Map
// This represents the value of the colors.
// The first level is a hashmap of the different arrays available
// The next two dimensions represent the columns and rows of colors.
_palettes: {
"3x3": [],
"3x2": ["/images/icons/1.png", "/images/icons/2.png", "/images/icons/3.png","/images/icons/4.png", "/images/icons/5.png", "/images/icons/6.png"]
},
// _imagePaths: Map
// This is stores the path to the palette images
// _imagePaths: {
// "3x3": dojo.moduleUrl("dijit", "templates/icons3x3.png")
// },
// _paletteCoords: Map
// This is a map that is used to calculate the coordinates of the
// images that make up the palette.
_paletteCoords: {
"leftOffset": 3, "topOffset": 3,
"cWidth": 50, "cHeight": 50
},
// templatePath: String
// Path to the template of this widget.
// templateString: dojo.cache("meemli", "templates/UploadPalette.html"),
templateString: template,
// _paletteDims: Object
// Size of the supported palettes for alignment purposes.
_paletteDims: {
"3x3": {"width": "156px", "height": "156px"}, // 48*3 + 3px left/top border + 3px right/bottom border...
"3x2": {"width": "156px", "height": "109px"} // 48*3 + 3px left/top border + 3px right/bottom border...
},
// tabIndex: String
// Widget tabindex.
maxCols: 3,
tabIndex: "0",
_curIndex: 0,
DoUpload: function(){
alert('hello');
uiFileInputDlg(); // function out in the workspace
},
_addImage: function(url) {
row = Math.floor(this._curIndex / this.maxCols);
col = this._curIndex - (row * this.maxCols);
this._curIndex++;
this._yDim = Math.floor(this._curIndex / this.maxCols);
this._xDim = this._curIndex - (row * this.maxCols);
var imgNode = dojo.doc.createElement("img");
imgNode.src = url;
//imgNode.style.height = imgNode.style.width = "48px";
var cellNode = dojo.doc.createElement("span");
cellNode.appendChild(imgNode);
cellNode.connectionRefs = new Array();
dojo.forEach(["Dijitclick", "MouseEnter", "Focus", "Blur"], function(handler) {
cellNode.connectionRefs.push(this.connect(cellNode, "on" + handler.toLowerCase(), "_onCell" + handler));
}, this);
this.divNode.appendChild(cellNode);
var cellStyle = cellNode.style;
cellStyle.top = this._paletteCoords.topOffset + (row * this._paletteCoords.cHeight) + "px";
cellStyle.left = this._paletteCoords.leftOffset + (col * this._paletteCoords.cWidth) + "px";
cellStyle.height = this._paletteCoords.cHeight + "px";
cellStyle.width = this._paletteCoords.cWidth + "px";
// console.debug( "tlhw: " + cellStyle.top + ", " + cellStyle.left + ", " + cellStyle.height + ", " + cellStyle.width );
// adjust size when the bits come...
// this.xh = this.xw = "32px";
//console.log('this.xh => ' + this.xh);
dojo.connect( imgNode,"onload", this, function() {
//console.log('IN: CONNECT...this.xh => ' + this.xh);
this.xh = imgNode.height;
this.xw = imgNode.width;
this.xh = (this.xh==0) ? this.xh="32px" : (this.xh + "");
this.xw = (this.xw==0) ? this.xw="32px" : (this.xw + "");
// var h = parseInt( this.xh );
// var w = parseInt( this.xw );
var hArr = this.xh.split('p');
var wArr = this.xw.split('p');
var h =hArr[0];
var w = wArr[0];
var THUMBNAIL_MAX_WIDTH = 50;
var THUMBNAIL_MAX_HEIGHT = 50;
var hLim = Math.min(THUMBNAIL_MAX_HEIGHT, this._paletteCoords.cHeight);
var wLim = Math.min(THUMBNAIL_MAX_WIDTH, this._paletteCoords.cWidth);
var scale = 1.0;
if( h > hLim || w > wLim ) {
if( h / w < 1.0 ) { // width is bigger than height
scale = wLim / w;
}
else {
scale = hLim / h;
}
}
imgNode.style.height = (scale * h) + "px";
imgNode.style.width = (scale * w) + "px";
console.debug( imgNode.src + ' loaded.'
+ "old: h " + h + ", w " + w + ", scale " + scale
+ ". new: h " + imgNode.style.height + ", w " + imgNode.style.width );
} );
if(dojo.isIE){
// hack to force event firing in IE
// image quirks doc'd in dojox/image/Lightbox.js :: show: function.
// imgNode.src = imgNode.src;
}
dojo.attr(cellNode, "tabindex", "-1");
dojo.addClass(cellNode, "imagePaletteCell");
dijit.setWaiRole(cellNode, "gridcell");
cellNode.index = this._cellNodes.length;
this._cellNodes.push(cellNode);
},
_clearImages: function() {
for(var i = 0; i < this._cellNodes.length; i++) {
this._cellNodes[i].parentNode.removeChild(this._cellNodes[i]);
}
this._currentFocus = 0;
this._curIndex = 0;
this._yDim = 0;
this._xDim = 0;
this._cellNodes = [];
},
setImages: function(imageList) {
this._clearImages();
for(var i = 0; i < imageList.length; i++) {
this._addImage(imageList[i]);
}
},
postCreate: function(){
// A name has to be given to the colorMap, this needs to be unique per Palette.
dojo.mixin(this.divNode.style, this._paletteDims[this.palette]);
// this.imageNode.setAttribute("src", this._imagePaths[this.palette]);
this.domNode.style.position = "relative";
this._cellNodes = [];
this.setImages(this._palettes[this.palette]);
this.connect(this.divNode, "onfocus", "_onDivNodeFocus");
this.connect(this.btnUpNode, "onclick", "DoUpload");
// Now set all events
// The palette itself is navigated to with the tab key on the keyboard
// Keyboard navigation within the Palette is with the arrow keys
// Spacebar selects the color.
// For the up key the index is changed by negative the x dimension.
var keyIncrementMap = {
UP_ARROW: -this._xDim,
// The down key the index is increase by the x dimension.
DOWN_ARROW: this._xDim,
// Right and left move the index by 1.
RIGHT_ARROW: 1,
LEFT_ARROW: -1
};
for(var key in keyIncrementMap){
this._connects.push(dijit.typematic.addKeyListener(this.domNode,
{keyCode:dojo.keys[key], ctrlKey:false, altKey:false, shiftKey:false},
this,
function(){
var increment = keyIncrementMap[key];
return function(count){ this._navigateByKey(increment, count); };
}(),
this.timeoutChangeRate, this.defaultTimeout));
}
},
focus: function(){
// summary:
// Focus this ColorPalette. Puts focus on the first swatch.
this._focusFirst();
},
onChange: function(url, hsz, wsz){
// summary:
// Callback when a image is selected.
// url, hsz, wsz, strings
// height and width string .
// console.debug("img selected: "+url);
},
_focusFirst: function(){
this._currentFocus = 0;
var cellNode = this._cellNodes[this._currentFocus];
window.setTimeout(function(){dijit.focus(cellNode);}, 0);
},
_onDivNodeFocus: function(evt){
// focus bubbles on Firefox 2, so just make sure that focus has really
// gone to the container
if(evt.target === this.divNode){
this._focusFirst();
}
},
_onFocus: function(){
// while focus is on the palette, set its tabindex to -1 so that on a
// shift-tab from a cell, the container is not in the tab order
dojo.attr(this.divNode, "tabindex", "-1");
},
_onBlur: function(){
this._removeCellHighlight(this._currentFocus);
// when focus leaves the palette, restore its tabindex, since it was
// modified by _onFocus().
dojo.attr(this.divNode, "tabindex", this.tabIndex);
},
_onCellDijitclick: function(/*Event*/ evt){
// summary:
// Handler for click, enter key & space key. Selects the color.
// evt:
// The event.
var target = evt.currentTarget;
if (this._currentFocus != target.index){
this._currentFocus = target.index;
window.setTimeout(function(){dijit.focus(target);}, 0);
}
this._selectColor(target);
dojo.stopEvent(evt);
},
_onCellMouseEnter: function(/*Event*/ evt){
// summary:
// Handler for onMouseOver. Put focus on the color under the mouse.
// evt:
// The mouse event.
var target = evt.currentTarget;
window.setTimeout(function(){dijit.focus(target);}, 0);
},
_onCellFocus: function(/*Event*/ evt){
// summary:
// Handler for onFocus. Removes highlight of
// the color that just lost focus, and highlights
// the new color.
// evt:
// The focus event.
this._removeCellHighlight(this._currentFocus);
this._currentFocus = evt.currentTarget.index;
dojo.addClass(evt.currentTarget, "imagePaletteCellHighlight");
},
_onCellBlur: function(/*Event*/ evt){
// summary:
// needed for Firefox 2 on Mac OS X
this._removeCellHighlight(this._currentFocus);
},
_removeCellHighlight: function(index){
dojo.removeClass(this._cellNodes[index], "imagePaletteCellHighlight");
},
_selectColor: function(selectNode){
// summary:
// This selects a color. It triggers the onChange event
// area:
// The area node that covers the color being selected.
var img = selectNode.getElementsByTagName("img")[0];
this.onChange(this.value = img.src, this.xh, this.xw);
},
_navigateByKey: function(increment, typeCount){
// summary:
// This is the callback for typematic.
// It changes the focus and the highlighed color.
// increment:
// How much the key is navigated.
// typeCount:
// How many times typematic has fired.
// typecount == -1 means the key is released.
if(typeCount == -1){ return; }
var newFocusIndex = this._currentFocus + increment;
if(newFocusIndex < this._cellNodes.length && newFocusIndex > -1)
{
var focusNode = this._cellNodes[newFocusIndex];
focusNode.focus();
}
}
});
});
Update
this.connect(this.btnUpNode, "onclick", "DoUpload");
to be
this.connect(this.btnUpNode, "onClick", "DoUpload");
onclick is a dom event, onClick is a dijit event. Since you are using a dijit button you want to use the latter.