How to display an interactive graticule overlay in react native maps [duplicate] - react-native

What I'm trying to do is, created 2 markers (they are draggable), there will be grid between them, like http://prntscr.com/4nx9f3.
When I change one of the marker, grid should be changed. I am trying to draw with polylines. By the way i can not get latitude or longitute with marker1.getPosition().lat().
all my code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
var marker1;
var marker2;
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(50.3, 44.3)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
marker1 = new google.maps.Marker({
position: new google.maps.LatLng(50.1, 44.1),
map: map,
draggable: true,
title: 'marker1 '
});
marker2 = new google.maps.Marker({
position: new google.maps.LatLng(50.5, 44.5),
map: map,
draggable: true,
title: 'marker2'
});
var flightPlanCoordinates = [
marker1.getPosition(),
marker2.getPosition(),
];
// code below is not working
/*
google.maps.event.addListener(marker1, 'dragend', function () {
polyline.LatLngBounds(new google.maps.LatLng(marker1.getPosition(), marker2.getPosition()));
});
google.maps.event.addListener(marker2, 'dragend', function () {
polyline.LatLngBounds(new google.maps.LatLng(marker1.getPosition(), marker2.getPosition()));
*/
var polyline = new google.maps.Polyline(
{ path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
var lat1 = marker1.getPosition().lat();
var lng1 = marker1.getPosition().lng();
var lat2 = marker2.getPosition().lat();
var lng2 = marker2.getPosition().lng();
// I tried to get distance between 2 markers but it did not work either
/* function distance(
lat1,
lng1,
lat2,
lng2
) {
var R = 6371;
var a =
0.5 - Math.cos((lat2 - lat1) * Math.PI / 180) / 2 +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
(1 - Math.cos((lon2 - lon1) * Math.PI / 180)) / 2;
return R * 2 * Math.asin(Math.sqrt(a));
}
*/
polyline.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

I think this is what you are trying to do. Changed your rectangleLng array to a two dimensional array and changed the excLat/excLng variables to not be rounded (they were backwards as well extLat wants to be up/down, excLng should be side to side).
proof of concept fiddle
code snippet:
var map;
var marker1;
var marker2;
var rectangle;
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(38.4, 26.7)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
marker1 = new google.maps.Marker({
position: new google.maps.LatLng(38.3, 26.6),
map: map,
draggable: true,
title: 'marker1'
});
google.maps.event.addListener(marker1, 'click', function(evt) {
infowindow.setContent(marker1.getPosition().toUrlValue(6));
infowindow.open(map, this);
});
marker2 = new google.maps.Marker({
position: new google.maps.LatLng(38.5, 26.8),
map: map,
draggable: true,
title: 'marker2'
});
google.maps.event.addListener(marker2, 'click', function(evt) {
infowindow.setContent(marker1.getPosition().toUrlValue(6));
infowindow.open(map, this);
});
rectangle = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: new google.maps.LatLngBounds(
marker1.getPosition(),
marker2.getPosition())
});
var leftSideDist = Math.round((marker2.getPosition().lng() - marker1.getPosition().lng()) * 10000) / 100;
var belowSideDist = Math.round((marker2.getPosition().lat() - marker1.getPosition().lat()) * 10000) / 100;
google.maps.event.addListener(marker1, 'dragend', function() {
rectangle.setBounds(new google.maps.LatLngBounds(marker1.getPosition(), marker2.getPosition()));
leftSideDist = Math.round((marker2.getPosition().lng() - marker1.getPosition().lng()) * 10000) / 100;
makeGrid();
});
google.maps.event.addListener(marker2, 'dragend', function() {
rectangle.setBounds(new google.maps.LatLngBounds(marker1.getPosition(), marker2.getPosition()));
belowSideDist = Math.round((marker2.getPosition().lat() - marker1.getPosition().lat()) * 10000) / 100;
makeGrid();
});
makeGrid();
}
var rectangleLat = [];
var rectangleLng = [];
function makeGrid() {
for (x in rectangleLng) {
for (y in rectangleLng[x]) {
if (rectangleLng[x][y].setMap) {
rectangleLng[x][y].setMap(null)
rectangleLng[x][y] = null;
}
}
}
var leftSideDist = marker2.getPosition().lng() - marker1.getPosition().lng();
var belowSideDist = marker2.getPosition().lat() - marker1.getPosition().lat();
var dividerLat = 5;
var dividerLng = 5; //ilerde kullanıcıdan alınacak
var excLat = belowSideDist / dividerLat;
var excLng = leftSideDist / dividerLng;
var m1Lat = marker1.getPosition().lat();
var m1Lng = marker1.getPosition().lng();
var m2Lat = marker2.getPosition().lat();
var m2Lng = marker2.getPosition().lng();
document.getElementById('info').innerHTML += "dividerLat=" + dividerLat + ", excLat=" + excLat + "<br>";
document.getElementById('info').innerHTML += "dividerLng=" + dividerLat + ", excLng=" + excLng + "<br>";
document.getElementById('info').innerHTML += "m1=" + marker1.getPosition().toUrlValue(6) + "<br>";
document.getElementById('info').innerHTML += "m2=" + marker2.getPosition().toUrlValue(6) + "<br>";
for (var i = 0; i < dividerLat; i++) {
if (!rectangleLng[i]) rectangleLng[i] = [];
for (var j = 0; j < dividerLng; j++) {
if (!rectangleLng[i][j]) rectangleLng[i][j] = {};
rectangleLng[i][j] = new google.maps.Rectangle({
strokeColor: '#FFFFFF',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.1,
map: map,
bounds: new google.maps.LatLngBounds(
new google.maps.LatLng(m1Lat + (excLat * i), m1Lng + (excLng * j)),
new google.maps.LatLng(m1Lat + (excLat * (i + 1)), m1Lng + (excLng * (j + 1))))
});
document.getElementById('info').innerHTML += "[i=" + i + ",j=" + j + "]:" + rectangleLng[i][j].getBounds() + "<br>";
} //for j Lng
} //for i Lat
document.getElementById('left').value = leftSideDist;
document.getElementById('blw').value = belowSideDist;
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
/* border: 1px solid #999;*/
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas"></div>
<div id="panel" style="margin-left:-320px">leftSideDist:
<input type="text" readonly id="left">belowSideDist:
<input type="text" readonly id="blw">
</div>
<div id="info"></div>

To get the coordinates of the marker after it's been dragged, change:
google.maps.event.addListener(marker1, 'dragend', function() {
polyline.LatLngBounds(new google.maps.LatLng(marker1.getPosition(), marker2.getPosition()));
});
to:
google.maps.event.addListener(marker1, 'dragend', function(event) {
polyline.LatLngBounds(event.latLng);
});
However, there is no LatLngBounds function on the polyline object.

As far as i done:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?
sensor=false&v=3&libraries=geometry"></script>
<script>
var map;
var marker1;
var marker2;
var rectangle;
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(38.4, 26.7)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
marker1 = new google.maps.Marker({
position: new google.maps.LatLng(38.3, 26.6),
map: map,
draggable: true,
title: 'marker1'
});
marker2 = new google.maps.Marker({
position: new google.maps.LatLng(38.5, 26.8),
map: map,
draggable: true,
title: 'marker2'
});
rectangle = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: new google.maps.LatLngBounds(
marker1.getPosition(),
marker2.getPosition())
});
var leftSideDist = Math.round((marker2.getPosition().lng() - marker1.getPosition().lng()) * 10000) / 100;
var belowSideDist = Math.round((marker2.getPosition().lat() - marker1.getPosition().lat()) * 10000) / 100;
google.maps.event.addListener(marker1, 'dragend', function () {
rectangle.setBounds(new google.maps.LatLngBounds(marker1.getPosition(), marker2.getPosition()));
leftSideDist = Math.round((marker2.getPosition().lng() - marker1.getPosition().lng()) * 10000) / 100;
});
google.maps.event.addListener(marker2, 'dragend', function () {
rectangle.setBounds(new google.maps.LatLngBounds(marker1.getPosition(), marker2.getPosition()));
belowSideDist = Math.round((marker2.getPosition().lat() - marker1.getPosition().lat()) * 10000) / 100;
});
var leftSideDist = Math.round((marker2.getPosition().lng() - marker1.getPosition().lng()) * 10000) / 100;
var belowSideDist = Math.round((marker2.getPosition().lat() - marker1.getPosition().lat()) * 10000) / 100;
var dividerLat = 5;
var dividerLng = 5; //ilerde kullanıcıdan alınacak
var excLat = leftSideDist / dividerLat;
var excLng = belowSideDist / dividerLng;
var rectangleLat[];
var rectangleLng[];
var m1Lat = marker1.getPosition().lat();
var m1Lng = marker1.getPosition().lng();
var m2Lat = marker2.getPosition().lat();
var m2Lng = marker2.getPosition().lng();
for (var i = 0; i < dividerLat; i++) {
for (var j = 0; j < dividerLng; j++) {
rectangleLng[i*5+j] = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: new google.maps.LatLngBounds(
( m1Lat , (excLng*(j+1) ) ),
( m1Lat+excLat, m2Lng+(excLng*(j+1) ) ) )
});
}//for j Lng
}//for i Lat
document.getElementById('left').value = leftSideDist;
document.getElementById('blw').value = belowSideDist;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="panel" style="margin-left:-320px">
leftSideDist: <input type="text" readonly id="left">
belowSideDist: <input type="text" readonly id="blw">
</div>
</body>
</html>

Related

OpenLayers 6.5.0: Features disappear when zooming in

When zooming in, all features disappear. The features are on either side of the antimeridian. In order to be able to use modify interaction, the geographical lengths of some features exceed the value of 180 degrees.
Any help is welcome!
var coords = [
[32100000, -7900000],
[28900000, -9700000],
[26300000, -10000000],
[23800000, -9300000],
[20400000, -6500000]
];
var osmLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var featuresLayer = new ol.layer.Vector({
source: new ol.source.Vector()
});
var map = new ol.Map({
layers: [osmLayer, featuresLayer],
target: document.getElementById("map")
});
var s = featuresLayer.getSource();
for (var i = 0; i < coords.length; i++) {
s.addFeature(new ol.Feature({
geometry: new ol.geom.Point(coords[i])
}));
}
map.setView(new ol.View({
center: coords[parseInt(coords.length / 2)],
zoom: 3,
maxZoom: 18,
minZoom: 3
}));
html,
body,
.map {
width: 100%;
height: 100%;
overflow: hidden;
}
<link href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.5.0/css/ol.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.5.0/build/ol.js"></script>
<div id="map" class="map"></div>
Per #Mike's comment, use new ol.source.Vector({wrapX: false}) if your coordinates exceed the normal world
var featuresLayer = new ol.layer.Vector({
source: new ol.source.Vector({wrapX: false})
});
updated code snippet:
var coords = [
[32100000, -7900000],
[28900000, -9700000],
[26300000, -10000000],
[23800000, -9300000],
[20400000, -6500000]
];
var osmLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var featuresLayer = new ol.layer.Vector({
source: new ol.source.Vector({wrapX: false})
});
var map = new ol.Map({
layers: [osmLayer, featuresLayer],
target: document.getElementById("map")
});
var s = featuresLayer.getSource();
for (var i = 0; i < coords.length; i++) {
s.addFeature(new ol.Feature({
geometry: new ol.geom.Point(coords[i])
}));
}
map.setView(new ol.View({
center: coords[parseInt(coords.length / 2)],
zoom: 3,
maxZoom: 18,
minZoom: 3
}));
html,
body,
.map {
width: 100%;
height: 100%;
overflow: hidden;
}
<link href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.5.0/css/ol.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.5.0/build/ol.js"></script>
<div id="map" class="map"></div>

ArcGIS Api For Javascript Filter Features Combined With Query Features

Iv been having trouble trying to combine the functionality between Filter by attribute and Query Features from a FeatureLayerView. Both samples are below;
https://developers.arcgis.com/javascript/latest/sample-code/featurefilter-attributes/index.html
https://developers.arcgis.com/javascript/latest/sample-code/featurelayerview-query/index.html
The aim is to apply the chosen filter (Filter feature by attribute), and this filter be applied to the Query FeatureLayerView showing in the side panel.
We have currently got both functionality working correctly in one sample, however they are still working in isolation from each other. I have added the code we have below.
Any help would be much appreciated.
<script src="https://js.arcgis.com/4.15/"></script>
<style>
html,
body,
#viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
#seasons-filter {
height: 160px;
width: 160px;
width: 100%;
visibility: hidden;
}
.season-item {
width: 100%;
padding: 12px;
text-align: center;
vertical-align: baseline;
cursor: pointer;
height: 40px;
height: 50px;
}
.season-item:focus {
background-color: dimgrey;
}
.season-item:hover {
background-color: dimgrey;
}
.panel-container {
position: relative;
width: 100%;
height: 100%;
}
.panel-side {
padding: 2px;
box-sizing: border-box;
width: 300px;
height: 100%;
position: absolute;
top: 0;
right: 0;
color: #fff;
background-color: rgba(0, 0, 0, 0.6);
overflow: auto;
z-index: 60;
}
.panel-side h3 {
padding: 0 20px;
margin: 20px 0;
}
.panel-side ul {
list-style: none;
margin: 0;
padding: 0;
}
.panel-side li {
list-style: none;
padding: 10px 20px;
}
.panel-result {
cursor: pointer;
margin: 2px 0;
background-color: rgba(0, 0, 0, 0.3);
}
.panel-result:hover,
.panel-result:focus {
color: orange;
background-color: rgba(0, 0, 0, 0.75);
}
</style>
<script>
require([
"esri/views/MapView",
"esri/Map",
"esri/layers/FeatureLayer",
"esri/widgets/Expand"
], function(MapView, Map, FeatureLayer, Expand) {
let floodLayerView;
let graphics;
const listNode = document.getElementById("nyc_graphics");
const popupTemplate = {
// autocasts as new PopupTemplate()
title: "{NAME} in {COUNTY}",
content: [
{
type: "fields",
fieldInfos: [
{
fieldName: "B12001_calc_pctMarriedE",
label: "% Married",
format: {
places: 0,
digitSeparator: true
}
}
]
}
]
};
// flash flood warnings layer
const layer = new FeatureLayer({
url:
"https://services.arcgis.com/P3ePLMYs2RVChkJx/ArcGIS/rest/services/ACS_Marital_Status_Boundaries/FeatureServer/2",
outFields: ["NAME", "GEOID"], // used by queryFeatures
popupTemplate: popupTemplate
});
const map = new Map({
basemap: "gray-vector",
layers: [layer]
});
const view = new MapView({
map: map,
container: "viewDiv",
center: [-73.95, 40.702],
zoom: 11
});
const seasonsNodes = document.querySelectorAll(`.season-item`);
const seasonsElement = document.getElementById("seasons-filter");
// click event handler for seasons choices
seasonsElement.addEventListener("click", filterBySeason);
// User clicked on Winter, Spring, Summer or Fall
// set an attribute filter on flood warnings layer view
// to display the warnings issued in that season
function filterBySeason(event) {
const selectedSeason = event.target.getAttribute("data-season");
floodLayerView.filter = {
where: "State = '" + selectedSeason + "'"
};
}
view.whenLayerView(layer).then(function(layerView) {
// flash flood warnings layer loaded
// get a reference to the flood warnings layerview
floodLayerView = layerView;
// set up UI items
seasonsElement.style.visibility = "visible";
const seasonsExpand = new Expand({
view: view,
content: seasonsElement,
expandIconClass: "esri-icon-filter",
group: "top-left"
});
//clear the filters when user closes the expand widget
seasonsExpand.watch("expanded", function() {
if (!seasonsExpand.expanded) {
floodLayerView.filter = null;
}
});
view.ui.add(seasonsExpand, "top-left");
});
// Start Of Side Bar Element
view.whenLayerView(layer).then(function(layerView) {
layerView.watch("updating", function(value) {
if (!value) {
// wait for the layer view to finish updating
// query all the features available for drawing.
layerView
.queryFeatures({
geometry: view.extent,
returnGeometry: true,
orderByFields: ["NAME"]
})
.then(function(results) {
graphics = results.features;
const fragment = document.createDocumentFragment();
graphics.forEach(function(result, index) {
const attributes = result.attributes;
const name = attributes.NAME;
// Create a list zip codes in NY
const li = document.createElement("li");
li.classList.add("panel-result");
li.tabIndex = 0;
li.setAttribute("data-result-id", index);
li.textContent = name;
fragment.appendChild(li);
});
// Empty the current list
listNode.innerHTML = "";
listNode.appendChild(fragment);
})
.catch(function(error) {
console.error("query failed: ", error);
});
}
});
});
// listen to click event on the zip code list
listNode.addEventListener("click", onListClickHandler);
function onListClickHandler(event) {
const target = event.target;
const resultId = target.getAttribute("data-result-id");
// get the graphic corresponding to the clicked zip code
const result =
resultId && graphics && graphics[parseInt(resultId, 10)];
if (result) {
// open the popup at the centroid of zip code polygon
// and set the popup's features which will populate popup content and title.
view
.goTo(result.geometry.extent.expand(2))
.then(function() {
view.popup.open({
features: [result],
location: result.geometry.centroid
});
})
.catch(function(error) {
if (error.name != "AbortError") {
console.error(error);
}
});
}
}
});
</script>
What you can do is filter the graphics you obtain with the query with a simple condition. Using both examples of ArcGIS, I put together what I think you are trying to get.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="initial-scale=1,maximum-scale=1,user-scalable=no"
/>
<title>Filter and Query - 4.15</title>
<link
rel="stylesheet"
href="https://js.arcgis.com/4.15/esri/themes/light/main.css"
/>
<script src="https://js.arcgis.com/4.15/"></script>
<style>
html,
body,
#viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
#seasons-filter {
height: 160px;
width: 100%;
visibility: hidden;
}
.season-item {
width: 100%;
padding: 12px;
text-align: center;
vertical-align: baseline;
cursor: pointer;
height: 40px;
}
.season-item:focus {
background-color: dimgrey;
}
.season-item:hover {
background-color: dimgrey;
}
#titleDiv {
padding: 10px;
}
#titleText {
font-size: 20pt;
font-weight: 60;
padding-bottom: 10px;
}
.panel-container {
position: relative;
width: 100%;
height: 100%;
}
.panel-side {
padding: 2px;
box-sizing: border-box;
width: 300px;
height: 100%;
position: absolute;
top: 0;
right: 0;
color: #fff;
background-color: rgba(0, 0, 0, 0.6);
overflow: auto;
z-index: 60;
}
.panel-side h3 {
padding: 0 20px;
margin: 20px 0;
}
.panel-side ul {
list-style: none;
margin: 0;
padding: 0;
}
.panel-side li {
list-style: none;
padding: 10px 20px;
}
.panel-result {
cursor: pointer;
margin: 2px 0;
background-color: rgba(0, 0, 0, 0.3);
}
.panel-result:hover,
.panel-result:focus {
color: orange;
background-color: rgba(0, 0, 0, 0.75);
}
</style>
<script>
require([
"esri/views/MapView",
"esri/Map",
"esri/layers/FeatureLayer",
"esri/widgets/Expand"
], function(MapView, Map, FeatureLayer, Expand) {
const listNode = document.getElementById("list_graphics");
const seasonsNodes = document.querySelectorAll(`.season-item`);
const seasonsElement = document.getElementById("seasons-filter");
let layer, map, view;
let selectedSeason = null;
let floodLayerView;
let graphics = null;
// functions
const filterBySeason = function (event) {
selectedSeason = event.target.getAttribute("data-season");
floodLayerView.filter = {
where: "Season = '" + selectedSeason + "'"
};
updateList();
};
const updateList = function () {
if (!graphics) {
return;
}
const fragment = document.createDocumentFragment();
graphics.forEach(function(result, index) {
const attributes = result.attributes;
if (!selectedSeason || attributes.SEASON === selectedSeason) {
const name = attributes.IssueDate;
// Create the list
const li = document.createElement("li");
li.classList.add("panel-result");
li.tabIndex = 0;
li.setAttribute("data-result-id", index);
li.textContent = name;
fragment.appendChild(li);
}
});
// Empty the current list
listNode.innerHTML = "";
listNode.appendChild(fragment);
};
// flash flood warnings layer
layer = new FeatureLayer({
portalItem: {
id: "f9e348953b3848ec8b69964d5bceae02"
},
outFields: ["SEASON", "IssueDate"]
});
map = new Map({
basemap: "gray-vector",
layers: [layer]
});
view = new MapView({
map: map,
container: "viewDiv",
center: [-98, 40],
zoom: 10
});
// click event handler for seasons choices
seasonsElement.addEventListener("click", filterBySeason);
view.whenLayerView(layer).then(function(layerView) {
/*
filter
*/
floodLayerView = layerView;
// set up UI items
seasonsElement.style.visibility = "visible";
const seasonsExpand = new Expand({
view: view,
content: seasonsElement,
expandIconClass: "esri-icon-filter",
group: "top-left"
});
//clear the filters when user closes the expand widget
seasonsExpand.watch("expanded", function() {
if (!seasonsExpand.expanded) {
floodLayerView.filter = null;
}
});
view.ui.add(seasonsExpand, "top-left");
view.ui.add("titleDiv", "bottom-left");
/*
query
*/
layerView.watch("updating", function(value) {
if (!value) {
// wait for the layer view to finish updating
// query all the features available for drawing.
layerView
.queryFeatures({
geometry: view.extent,
returnGeometry: true,
orderByFields: ["IssueDate"]
})
.then(function (results) {
graphics = results.features;
updateList();
})
.catch(function(error) {
console.error("query failed: ", error);
});
}
});
});
/*
query
*/
// listen to click event on list items
listNode.addEventListener("click", onListClickHandler);
function onListClickHandler(event) {
const target = event.target;
const resultId = target.getAttribute("data-result-id");
// get the graphic corresponding to the clicked item
const result =
resultId && graphics && graphics[parseInt(resultId, 10)];
if (result) {
// open the popup at the centroid of polygon
// and set the popup's features which will populate popup content and title.
view
.goTo(result.geometry.extent.expand(2))
.then(function() {
view.popup.open({
features: [result],
location: result.geometry.centroid
});
})
.catch(function(error) {
if (error.name != "AbortError") {
console.error(error);
}
});
}
};
});
</script>
</head>
<body>
<div class="panel-container">
<div id="seasons-filter" class="esri-widget">
<div class="season-item visible-season" data-season="Winter">Winter</div>
<div class="season-item visible-season" data-season="Spring">Spring</div>
<div class="season-item visible-season" data-season="Summer">Summer</div>
<div class="season-item visible-season" data-season="Fall">Fall</div>
</div>
<div class="panel-side esri-widget">
<ul id="list_graphics">
<li>Loading…</li>
</ul>
</div>
<div id="viewDiv"></div>
<div id="titleDiv" class="esri-widget">
<div id="titleText">Flash Floods by Season</div>
<div>Flash Flood Warnings (2002 - 2012)</div>
</div>
</div>
</body>
</html>
I just move things a bit so that each time the user filter with the seasons the list of the side panel is updated.
Now, you will see that I do not query on a new season, I just filter the graphics that we already have.
Each time a new query is made, the list is going to filter in the same manner.
Im also trying to add an option within the dropdown list to clear or filters and reset the side panel. I have added an on-click event, which clears the filters, but it doesn't reset the side panel.
Any help would be much appreciated.
require([
"esri/views/MapView",
"esri/Map",
"esri/layers/FeatureLayer",
"esri/widgets/Expand"
], function(MapView, Map, FeatureLayer, Expand) {
const listNode = document.getElementById("list_graphics");
const seasonsNodes = document.querySelectorAll(`.season-item`);
const seasonsElement = document.getElementById("seasons-filter");
let layer, map, view;
let selectedSeason = null;
let floodLayerView;
let graphics = null;
// functions
const filterBySeason = function (event) {
selectedSeason = event.target.getAttribute("data-season");
floodLayerView.filter = {
where: "Season = '" + selectedSeason + "'"
};
document
.getElementById("filterReset")
.addEventListener("click", function() {
floodLayerView.filter = selectedSeason;
});
updateList();
};
const updateList = function () {
if (!graphics) {
return;
}
const fragment = document.createDocumentFragment();
graphics.forEach(function(result, index) {
const attributes = result.attributes;
if (!selectedSeason || attributes.SEASON === selectedSeason) {
const name = attributes.IssueDate;
// Create the list
const li = document.createElement("li");
li.classList.add("panel-result");
li.tabIndex = 0;
li.setAttribute("data-result-id", index);
li.textContent = name;
fragment.appendChild(li);
}
});
// Empty the current list
listNode.innerHTML = "";
listNode.appendChild(fragment);
};
// flash flood warnings layer
layer = new FeatureLayer({
portalItem: {
id: "f9e348953b3848ec8b69964d5bceae02"
},
outFields: ["SEASON", "IssueDate"]
});
map = new Map({
basemap: "gray-vector",
layers: [layer]
});
view = new MapView({
map: map,
container: "viewDiv",
center: [-98, 40],
zoom: 10
});
// click event handler for seasons choices
seasonsElement.addEventListener("click", filterBySeason);
view.whenLayerView(layer).then(function(layerView) {
/*
filter
*/
floodLayerView = layerView;
// set up UI items
seasonsElement.style.visibility = "visible";
const seasonsExpand = new Expand({
view: view,
content: seasonsElement,
expandIconClass: "esri-icon-filter",
group: "top-left"
});
//clear the filters when user closes the expand widget
view.ui.add(seasonsExpand, "top-left");
view.ui.add("titleDiv", "bottom-left");
/*
query
*/
layerView.watch("updating", function(value) {
if (!value) {
// wait for the layer view to finish updating
// query all the features available for drawing.
layerView
.queryFeatures({
geometry: view.extent,
returnGeometry: true,
orderByFields: ["IssueDate"]
})
.then(function (results) {
graphics = results.features;
updateList();
})
.catch(function(error) {
console.error("query failed: ", error);
});
}
});
});
/*
query
*/
// listen to click event on list items
listNode.addEventListener("click", onListClickHandler);
function onListClickHandler(event) {
const target = event.target;
const resultId = target.getAttribute("data-result-id");
// get the graphic corresponding to the clicked item
const result =
resultId && graphics && graphics[parseInt(resultId, 10)];
if (result) {
// open the popup at the centroid of polygon
// and set the popup's features which will populate popup content and title.
view
.goTo(result.geometry.extent.expand(2))
.then(function() {
view.popup.open({
features: [result],
location: result.geometry.centroid
});
})
.catch(function(error) {
if (error.name != "AbortError") {
console.error(error);
}
});
}
};
});
</script>```

Animate div elements

How can I cause these div elements to stop and return to their starting position once they collide with one another? I tried adjusting adding to the pixels in the function, but that didn't work.
For example, I tried elem.style.right = pos + '100px'. When I tried this the div element ended up not moving at all.
You can try some form of collision detection. See the collisionDetection method below.
let leftIntervalId;
var leftElem = document.getElementById("myAnimation");
function myMove() {
var pos = 0;
leftIntervalId = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(leftIntervalId);
} else {
pos++;
leftElem.style.top = pos + 'px';
leftElem.style.left = pos + 'px';
}
}
}
const rightElem = document.getElementById("Animation");
function Move() {
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
rightElem.style.top = pos + 'px';
rightElem.style.right = pos + 'px';
collisionDetection(parseInt(leftElem.style.left.replace(/px/, "")), pos,
leftIntervalId, id);
}
}
}
function collisionDetection(leftPos, rightPos, leftIntervalId, rightIntervalId) {
if (leftPos + 100 > 400 - rightPos) {
clearInterval(leftIntervalId);
clearInterval(rightIntervalId);
setTimeout(function() {
leftElem.style.top = '0px';
leftElem.style.left = '0px';
rightElem.style.top = '0px';
rightElem.style.right = '0px';
},
500);
}
}
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: #eee;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
#Animation {
width: 50px;
height: 50px;
position: absolute;
right: 0;
background-color: blue;
}
<p>
<button onclick="myMove(); Move()">Click Me</button>
</p>
<div id="myContainer">
<div id="myAnimation"></div>
<div id="Animation"></div>
</div>

KineticJS mouse position of image

I have a image like this
var image = new Kinetic.Image({
x : x,
y : y,
width : 1000,
height :100,
image : image,
});
How do I get the mouse position based on the image.
according this example, I could get position Object{0, 0} ~ {100, 1000}
I only found an api stage.getPointerPosition()
If you want to get mouse position on click then you can do this:
image.on('click', function(){
var mousePos = youStage.getPointerPosition();
var p = { x: mousePos.x, y: mousePos.y }; // p is a clone of mousePos
var r = image.getAbsoluteTransform().copy().invert().point(mousePos);
});
Please find the working example below albeit it uses KonvaJS but the concept is same. And you should also start using Konva cause it's well maintained and documented.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/konvajs/konva/1.4.0/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Image Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var imageObj = new Image();
imageObj.onload = function() {
var yoda = new Konva.Image({
x: 50,
y: 50,
image: imageObj,
width: 106,
height: 118
});
yoda.on('click', function() {
var mousePos = stage.getPointerPosition();
var p = {
x: mousePos.x,
y: mousePos.y
}; // p is a clone of mousePos
var r = yoda.getAbsoluteTransform().copy().invert().point(mousePos);
console.log(r);
});
// add the shape to the layer
layer.add(yoda);
// add the layer to the stage
stage.add(layer);
};
imageObj.src = 'https://upload.wikimedia.org/wikipedia/en/thumb/9/9b/Yoda_Empire_Strikes_Back.png/220px-Yoda_Empire_Strikes_Back.png';
</script>
</body>
</html>

cytoscape js event when all elements rendered?

Is there an event emitted when cy.add(elements) is finished? It appears there's an event fired for each element added, but I don't see an event when all elements have been added and rendered.
ex:
var elements = [ { data: {id: 'n1'} }, { data: {id: 'n2'} }, { data: {id: 'n3'} }, ];
cy.add(elements);
cy.on('add',function(evt){
console.log('Element Added')
})
The log will run three times.
Update I refactored per your comment. This will allow you to detect and do something after each "batch" is added.
I started with an example from the cytoscape.js website and heavily edited it for this answer.
You will probably want to run the snippet full screen to see the canvas and the console at the same time.
// For generating new IDs
var ids = [];
function newId() {
if (!ids.length) {
ids.push('1');
} else {
var id = '' + (parseInt(ids[ids.length - 1]) + 1);
ids.push(id);
}
return ids[ids.length - 1];
}
// Draw for first time
var cy = cytoscape({
container: document.getElementById('cy'),
elements: [], // don't add elements initially
style: [{
selector: 'node',
style: {
'background-color': '#666',
'label': 'data(id)',
'width': 10,
'height': 10
}
}, {
selector: 'edge',
style: {
'width': 3,
'line-color': '#ccc',
'target-arrow-color': '#ccc',
'target-arrow-shape': 'triangle'
}
}],
layout: {
name: 'grid',
rows: 1
}
});
var batchTotal = 0;
var totalAdded = 0;
// Start listening to events
cy.on('add', function(evt) {
console.log('event heard: add');
if (totalAdded < batchTotal) {
totalAdded++;
}
console.log('totalAdded/batchTotal: ', totalAdded + '/' + batchTotal);
if (totalAdded == batchTotal) {
console.log('entire batch added');
// do whatever you want!
}
});
var xStart = 10;
var x = xStart;
var y = 40;
var xInc = 20;
var yInc = 30;
var max = 200;
var addTotal = 2;
// For adding new elements
function add() {
// let's build multiple elements to add at once
var elements = [];
var id;
var el;
for (var i = 0; i < addTotal; i++) {
id = newId();
el = {
data: {
id: id
},
position: {
x: x,
y: y
}
};
elements.push(el);
if (x <= max) {
x += xInc;
} else {
x = xStart;
y += yInc;
}
}
addElements(elements);
}
// wrap the cy.add() method
// so we can inject our total counter
function addElements (elements) {
if (!Array.isArray(elements)) elements = [elements]; // convert to array
// this would be useful in a more robust app where
// addTotal may change
batchTotal = elements.length;
// reset
totalAdded = 0;
cy.add(elements);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>CytoscapeJS Example</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/2.7.0/cytoscape.js"></script>
<style type="text/css">
#cy {
width: 300px;
height: 300px;
display: block;
}
</style>
</head>
<body>
<button onclick="add()">Add</button>
<p>Click add and watch the console. Look for the <strong>entire batch added</strong> message.</p>
<div id="cy"></div>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>