vue 3 mapbox-gl-draw How to react to events correctly - vue.js

I have a code that draws objects on the map, but I don't understand how to save them and in which part of the code to respond correctly to events
mounted(){
this.initMap()
}
methods:{
initMap(){
this.map = new mapboxgl.Map({
container: 'mapContainer', // container ID
style: 'mapbox://styles/mapbox/satellite-streets-v11', // style URL
center: this.centerCoordinates, // starting position [lng, lat]
zoom: 13 // starting zoom
});
this.draw = new MapboxDraw();
this.map.addControl(this.draw);
console.log(this.draw.getAll());
let tmp = null
this.map.on('draw.create', function (e) {
let tmp = e.features[0].geometry
console.log(tmp)
});
this.draw.add(tmp)
},
}

Related

Add more features to the feature layer

Here is a piece of code to add a polygon, its 'name' (PERMIT_AREA) and description to the feature layer. My problem is the drawn polygon is not applying to the layer. How we can add more details such as name and description to the layer? Can you please correct my code,
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());
const query = {
geometry: queryGeometry,
outFields: ["*"],
attributes: {
PERMIT_AREA:'sample PERMIT_AREA'
}
};
console.log(query);
lyrpermitAreaUrl.queryFeatures(query).then(function (results) {
var lyr = results.features;
selectFeatures(lyr);
});
}
});
});
// 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(geometryabc) {
console.log(geometryabc);
// create a query and set its geometry parameter to the
// rectangle that was drawn on the view
lyrpermitAreaUrl.applyEdits({ addFeatures: [geometryabc] }).then((editsResult) => {
console.log(editsResult);
console.log(editsResult.addFeatureResults[0].objectId);
});
}
I have edited the code like provided below. Now I can apply user entered polygon to feature layer,
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",
"esri/Graphic",
],
function (esriConfig, Map, MapView, FeatureLayer, TileLayer, VectorTileLayer, GraphicsLayer, Search, SketchViewModel, geometryEngineAsync, Graphic) {
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 lyrpermitAreaUrl = 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],
// center: [-118.80500, 34.02700], //Longitude, latitude
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());
var rawrings = queryGeometry.rings;
var rings = [];
console.log('rings here');
for (var i = 0; i < rawrings.length; i++) {
rings.push(rawrings[i]);
// graphics.push(graphic);
console.log(rawrings[i]);
}
console.log(rings[0]);
// Create a polygon geometry
const polygon = {
type: "polygon",
spatialReference: {
wkid: 102704, //102704,
},
rings: [rings[0]]
};
const simpleFillSymbol = {
type: "simple-fill",
color: [227, 139, 79, 0.8], // Orange, opacity 80%
outline: {
color: [255, 255, 255],
width: 1
}
};
const polygonGraphic = new Graphic({
geometry: polygon,
symbol: simpleFillSymbol,
});
graphicsLayer.add(polygonGraphic);
// const addEdits = {
// addFeatures: polygonGraphic
// };
console.log('here');
// console.log(addEdits);
// apply the edits to the layer
selectFeatures(polygonGraphic);
}
});
});
// 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(geometryabc) {
console.log(geometryabc);
// create a query and set its geometry parameter to the
// rectangle that was drawn on the view
lyrpermitAreaUrl.applyEdits({ addFeatures: [geometryabc] }).then((editsResult) => {
console.log(editsResult);
console.log(editsResult.addFeatureResults[0].objectId);
});
}
// search widget
const searchWidget = new Search({
view: view,
});
view.ui.add(searchWidget, {
position: "top-left",
index: 2
});
});
I have added the attributes like below,
var attr = {"NETSUITE_USERID":"test user","PERMIT_AREA":"test permit area","COMMENTS":"test comments"};
const polygonGraphic = new Graphic({
geometry: polygon,
symbol: simpleFillSymbol,
attributes: attr
});
If I understand then, you need a new Graphic with the sketched geometry and the attributes you query. Something like this might work,
sketchViewModel.on("create", async (event) => {
if (event.state === "complete") {
// remove the graphic from the layer. Sketch adds
// the completed graphic to the layer by default.
graphicsLayer.remove(event.graphic);
const newGeometry = event.graphic.geometry;
const query = {
geometry: newGeometry,
outFields: ["NAME", "DESCRIPTION"],
returnGeometry: false
};
lyrpermitAreaUrl.queryFeatures(query).then(function (results) {
if (!results.features) {
return;
}
const data = results.features[0].attributes;
const newGraphic = new Graphic({
geometry: newGeometry,
attributes: {
"NAME": data["NAME"],
"DESCRIPTION": data["DESCRIPTION"]
}
});
lyrpermitAreaUrl.applyEdits({ addFeatures: [newGraphic] }).then((editsResult) => {
console.log(editsResult);
});
});
}
});
NAME and DESCRIPTION are sample attributes name, you should use the ones you need.

Graphic items not refreshing when dragging MapView

Is there any way to make the centered point to move whilst dragging the map? It seems currently its not possible to add graphics nor remove them whilst dragging happens.
require([
"esri/Map",
"esri/views/MapView",
"esri/Graphic",
"esri/core/watchUtils",
"dojo/domReady!"
], function(
Map,
MapView,
Graphic,
watchUtils
){
var map = new Map({
basemap: "hybrid"
});
var view = new MapView({
container: "map",
map: map,
constraints: {
rotationEnabled:false
}
});
var addPoint = function(point){
view.graphics.removeAll();
var graphicPoint = {
type: "point",
latitude: point.latitude,
longitude: point.longitude
};
var markerSymbol = {
type: "simple-marker",
color: [85,139,197],
outline: {
color: [255,255,255],
width:2
}
};
var pointGraphic = new Graphic({
geometry: graphicPoint,
symbol: markerSymbol
});
view.graphics.add(pointGraphic);
};
var centerPoint = function(){
var point = view.center;
var input = document.getElementById("myInput");
input.value = point.latitude.toFixed(5) + " " + point.longitude.toFixed(5);
addPoint(point);
};
var showCenterCoords = function(){
centerPoint();
view.on("pointer-move", function(e){
centerPoint();
});
};
view.when(function(){
showCenterCoords();
});
});
https://jsfiddle.net/wrtqn2e3/3/
Im using Esri Js API 4.8.
If you look at the INPUT window, you can see that the "pointer-move" event triggers, because coordinates do refresh even on dragging.
Is there a possible workaround for this to happen?
Thanks in advance.

Add markercluster Google Maps V3

I using code like in this page. how can I add marker cluster?
Thanks.
[Google Map v3 auto refresh Markers only
Sample script...
$(function() {
var locations = {};//A repository for markers (and the data from which they were constructed).
//initial dataset for markers
var locs = {
1: { info:'11111. Some random info here', lat:-37.8139, lng:144.9634 },
2: { info:'22222. Some random info here', lat:46.0553, lng:14.5144 },
3: { info:'33333. Some random info here', lat:-33.7333, lng:151.0833 },
4: { info:'44444. Some random info here', lat:27.9798, lng:-81.731 }
};
var map = new google.maps.Map(document.getElementById('map_2385853'), {
zoom: 1,
maxZoom: 8,
minZoom: 1,
streetViewControl: false,
center: new google.maps.LatLng(40, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var auto_remove = true;//When true, markers for all unreported locs will be removed.
function setMarkers(locObj) {
if(auto_remove) {
//Remove markers for all unreported locs, and the corrsponding locations entry.
$.each(locations, function(key) {
if(!locObj[key]) {
if(locations[key].marker) {
locations[key].marker.setMap(null);
}
delete locations[key];
}
});
}
$.each(locObj, function(key, loc) {
if(!locations[key] && loc.lat!==undefined && loc.lng!==undefined) {
//Marker has not yet been made (and there's enough data to create one).
//Create marker
loc.marker = new google.maps.Marker({
position: new google.maps.LatLng(loc.lat, loc.lng),
map: map
});
//Attach click listener to marker
google.maps.event.addListener(loc.marker, 'click', (function(key) {
return function() {
infowindow.setContent(locations[key].info);
infowindow.open(map, locations[key].marker);
}
})(key));
//Remember loc in the `locations` so its info can be displayed and so its marker can be deleted.
locations[key] = loc;
}
else if(locations[key] && loc.remove) {
//Remove marker from map
if(locations[key].marker) {
locations[key].marker.setMap(null);
}
//Remove element from `locations`
delete locations[key];
}
else if(locations[key]) {
//Update the previous data object with the latest data.
$.extend(locations[key], loc);
if(loc.lat!==undefined && loc.lng!==undefined) {
//Update marker position (maybe not necessary but doesn't hurt).
locations[key].marker.setPosition(
new google.maps.LatLng(loc.lat, loc.lng)
);
}
//locations[key].info looks after itself.
}
});
}
var ajaxObj = {//Object to save cluttering the namespace.
options: {
url: "........",//The resource that delivers loc data.
dataType: "json"//The type of data tp be returned by the server.
},
delay: 10000,//(milliseconds) the interval between successive gets.
errorCount: 0,//running total of ajax errors.
errorThreshold: 5,//the number of ajax errors beyond which the get cycle should cease.
ticker: null,//setTimeout reference - allows the get cycle to be cancelled with clearTimeout(ajaxObj.ticker);
get: function() { //a function which initiates
if(ajaxObj.errorCount < ajaxObj.errorThreshold) {
ajaxObj.ticker = setTimeout(getMarkerData, ajaxObj.delay);
}
},
fail: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
ajaxObj.errorCount++;
}
};
//Ajax master routine
function getMarkerData() {
$.ajax(ajaxObj.options)
.done(setMarkers) //fires when ajax returns successfully
.fail(ajaxObj.fail) //fires when an ajax error occurs
.always(ajaxObj.get); //fires after ajax success or ajax error
}
setMarkers(locs);//Create markers from the initial dataset served with the document.
//ajaxObj.get();//Start the get cycle.
// *******************
//test: simulated ajax
/*
var testLocs = {
1: { info:'1. New Random info and new position', lat:-37, lng:124.9634 },//update info and position and
2: { lat:70, lng:14.5144 },//update position
3: { info:'3. New Random info' },//update info
4: { remove: true },//remove marker
5: { info:'55555. Added', lat:-37, lng:0 }//add new marker
};
setTimeout(function() {
setMarkers(testLocs);
}, ajaxObj.delay);
*/
// *******************
});

containingTab cause on undefined is not an object

In my titanium based application,My navigation flow as like the following
HomeVu -> Subvu1 -> Subvu2
While am trying to navigate from Subvu1 view to Subvu2 it shows an error that
Script Error
{
backtrace = "#0 () at :0";
line = 40;
message = "'undefined' is not an object (evaluating 'ReportSubWindow.containingTab.open')";
name = TypeError;
sourceId = 300153536;
sourceURL = "file:///Users/administrator/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/9A6B5752-F198-48AC-9E23-2A0DC31A2BD2/test.app/SubVu/text.js";
}
Here the code
HomeVu
button2.addEventListener('click', function()
{
var FindAnExpertSubWindow = require('SubVu/email');
self.containingTab.open(new FindAnExpertSubWindow('My Mail'));
});
Subvu1
function FindAnExpertSubWindow(title)
{
var findAnExpertSubWin = Ti.UI.createWindow({
backgroundColor : 'white', });
var button1 = Ti.UI.createButton({
backgroundImage: 'ui/images/Untitled.png',
height:32,
width:87,
top:90,
left:115,
});
button1.addEventListener('click', function()
{
var FindAnExpertSubWindow = require('SubVu/email');
findAnExpertSubWin.containingTab.open(new FindAnExpertSubWindow('My Mail'));
});
findAnExpertSubWin.add(button1);
return findAnExpertSubWin;
};
module.exports = FindAnExpertSubWindow;
Subvu2
function ReportSubWindow(title)
{
var reportSubWin = Ti.UI.createWindow({
backgroundColor : 'black',
});
return reportSubWin;
};
module.exports = ReportSubWindow;
How to navigate from Subvu1 to Subvu2?
When you are creating Subvu1 window you have to set containingTab property the same way as you do in HomeVu window. Your code example is missing that part of code but probably it could look like this:
HomeVu
button2.addEventListener('click', function() {
var FindAnExpertSubWindow = require('SubVu/email');
self.containingTab.open(new FindAnExpertSubWindow('My Mail', self.containingTab));
});
Subvu1
function FindAnExpertSubWindow(title, containingTab) {
var findAnExpertSubWin = Ti.UI.createWindow({
backgroundColor : 'white',
containingTab: containingTab,
});
/* ... */
});
Another way of solving is to stop passing reference to Tab object between every Window and just create one global object, which you will use for opening new windows.
If it doesn't help, post more example code.

Reverse Geocoding With Dynamic Form

I've been trying to find a way to use the 'Reverse Geocoding' service with the Latitude and Longitude co-ordinates coming from two text boxes on my HTML form, and I must admit I'm not really sure what I need to do.
I have managed to do this with the 'Geocode' service (see code below), but I just wondered whether someone may be able to point me in the right direction of how I could adapt the 'Geocode' javascript I have to the 'Reverse Geocoging' service.
(function Geocode() {
// This is defining the global variables
var map, geocoder, myMarker;
window.onload = function() {
//This is creating the map with the desired options
var myOptions = {
zoom: 5,
center: new google.maps.LatLng(55.378051,-3.435973),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.BOTTOM
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_RIGHT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
}
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
// This is making the link with the 'Search For Location' HTML form
var form = document.getElementById('SearchForLocationForm');
// This is catching the forms submit event
form.onsubmit = function() {
// This is getting the Address from the HTML forms 'Address' text box
var address = document.getElementById('GeocodeAddress').value;
// This is making the Geocoder call
getCoordinates(address);
// This is preventing the form from doing a page submit
return false;
}
}
// This creates the function that will return the coordinates for the address
function getCoordinates(address) {
// This checks to see if there is already a geocoded object. If not, it creates one
if(!geocoder) {
geocoder = new google.maps.Geocoder();
}
// This is creating a GeocoderRequest object
var geocoderRequest = {
address: address
}
// This is making the Geocode request
geocoder.geocode(geocoderRequest, function(results, status) {
// This checks to see if the Status is 'OK 'before proceeding
if (status == google.maps.GeocoderStatus.OK) {
// This centres the map on the returned location
map.setCenter(results[0].geometry.location);
// This creates a new marker and adds it to the map
var myMarker = new google.maps.Marker({
map: map,
zoom: 12,
position: results[0].geometry.location,
draggable:true
});
//This fills out the 'Latitude' and 'Longitude' text boxes on the HTML form
document.getElementById('Latitude').value= results[0].geometry.location.lat();
document.getElementById('Longitude').value= results[0].geometry.location.lng();
//This allows the marker to be draggable and tells the 'Latitude' and 'Longitude' text boxes on the HTML form to update with the new co-ordinates as the marker is dragged
google.maps.event.addListener(
myMarker,
'dragend',
function() {
document.getElementById('Latitude').value = myMarker.position.lat();
document.getElementById('Longitude').value = myMarker.position.lng();
var point = myMarker.getPosition();
map.panTo(point);
}
);
}
}
)
}
})();
UPDATE
Firstly, many thanks for the code you kindly posted and the suggestion to go and have a look at the Google documentation.
From what you suggested, and from what I took from the additional documentation I came up with the following. However, when I click my submit button nothing happens, almost as if there is no command attached to it. I don't receive any error messages and I've checked to make sure that I've linked the code to the correct fieldnames and all seems ok. I just wondered whether it would be at all possible if you, or indeed anyone else, could take a look at it please to tell me where I've gone wrong.
Many thanks and kind regards
(function ReverseGeocode() {
var form, geocoderRequest, latlng, myMarker, point;
window.onload = function() {
//This is creating the map with the desired options
var myOptions = {
zoom: 5,
center: new google.maps.LatLng(55.378051,-3.435973),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.BOTTOM
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_RIGHT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
}
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
var latlng = new google.maps.LatLng('Latitude', 'Longitude');
// This is making the Geocode request
geocoder.geocode({'LatLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
var myMarker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
//This fills out the 'Address' text boxe on the HTML form
document.getElementById('Address').value= results[0].geometry.location.latlng();
var point = myMarker.getPosition();
map.panTo(point);
}
}
}
)}})
Once you have the latitude and longitude from your form, you do something like this (using your above code as a starting point, for the sake of clarity):
var latlng = new google.maps.LatLng(latitudeFromForm,longitudeFromForm);
// This is creating a GeocoderRequest object
var geocoderRequest = {
'latlng':latlng
}
// This is making the Geocode request
geocoder.geocode(geocoderRequest, function(results, status) {
// This checks to see if the Status is 'OK 'before proceeding
if (status == google.maps.GeocoderStatus.OK) {
// Do stuff with the result here
}
If you haven't read it yet, you may want to read the Reverse Geocoding section of http://code.google.com/apis/maps/documentation/javascript/services.html#ReverseGeocoding.