ArcGIS 3.x to 4.x Migration - geojson

I was using ArcGIS JS API 3.10 and have a Github
repository to display GeoJSON data on a map but now I have to upgrade to
4.9 version I read 3.x to 4.x migration document published by ESRI and apply he changes like link location etc. but it’s not working anymore.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7,IE=9">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>ArcGIS GeoJSON Layer</title>
<!-- ArcGIS API for JavaScript CSS-->
<link rel="stylesheet" href="https://js.arcgis.com/4.9/esri/css/main.css">
#*<link rel="stylesheet" href="//js.arcgis.com/3.9/js/esri/css/esri.css">*#
<!-- Web Framework CSS - Bootstrap (getbootstrap.com) and Bootstrap-map-js (github.com/esri/bootstrap-map-js) -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="//esri.github.io/bootstrap-map-js/src/css/bootstrapmap.css">
<style>
html, body, #mapDiv {
height: 500px;
width: 100%;
}
</style>
<script src="https://js.arcgis.com/4.9/"></script>
<!-- ArcGIS API for JavaScript library references -->
#*<script src="//js.arcgis.com/3.10"></script>*#
<!-- Terraformer reference -->
<script src="/vendor/terraformer/terraformer.min.js"></script>
<script src="/vendor/terraformer-arcgis-parser/terraformer-arcgis-parser.min.js"></script>
<script>
require(["esri/Map",
"/Scripts/Refine.js",
"dojo/on",
"dojo/dom",
"dojo/domReady!"],
function (Map, GeoJsonLayer, on, dom) {
// Create map
var map = new Map("mapDiv", {
basemap: "gray",
center: [-122.5, 45.5],
zoom: 5
});
map.on("load", function () {
addGeoJsonLayer("http://113.197.55.251/api/punjab");
});
// Add the layer
function addGeoJsonLayer(url) {
// Create the layer
var geoJsonLayer = new GeoJsonLayer({
url: url
});
// Zoom to layer
geoJsonLayer.on("update-end", function (e) {
map.setExtent(e.target.extent.expand(1.2));
});
// Add to map
map.add(geoJsonLayer);
}
});
</script>
</head>
<body>
<div id="mapDiv"></div>
</body>
</html>

In ArcGIS 4.9 you have to use a MapView like below:
For the conversion between GeoJson and EsriJson, I suggest you the arcgis-to-geojson-utils library
Import the library in your html:
<script src="https://unpkg.com/#esri/arcgis-to-geojson-utils"></script>
javascript:
require([
"esri/Map",
"esri/views/MapView",
"esri/Graphic",
"esri/layers/FeatureLayer",
"esri/layers/support/Field",
"dojo/on",
"dojo/dom",
"dojo/domReady!"],
function (Map, MapView, Graphic, FeatureLayer, Field, on, dom) {
// Create mapView and map
var mapView = new MapView({
container: mapDiv,
map: new Map({
basemap: "gray"
}),
center: [-122.5, 45.5],
zoom: 5
}).when(function(mapView) {
makeRequest("http://113.197.55.251/api/punjab", function(response) {
createLayerFromGeoJSON(response, mapView);
});
});
// Request the geojson data using XmlHttpRequest
function makeRequest(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(JSON.parse(xhr.response));
}
};
xhr.onerror = function(error) {
throw error;
}
xhr.send();
};
// Create the layer from the geojson data
function createLayerFromGeoJSON(geojson, mapView) {
// Convert geojson to esriJson using arcgis-to-geojson-utils library
var esriJson = ArcgisToGeojsonUtils.geojsonToArcGIS(geojson);
// Create an array of graphics from the esriJson
var graphics = esriJson.map(function(feature, i) {
return new Graphic({
geometry: {
type: "polygon",
rings: feature.geometry.rings
},
attributes: {
ObjectID: i,
Name: feature.attributes.Name
}
});
});
// Create a FeatureLayer from the graphics
var layer = new FeatureLayer({
title: "My feature layer",
source: graphics, // autocast as an array of esri/Graphic
geometryType: "polygon",
fields: [
new Field({
name: "ObjectID",
alias: "ObjectID",
type: "oid"
}),
new Field({
name: "Name",
alias: "Name",
type: "string"
}),
],
objectIdField: "ObjectID", // This must be defined when creating a layer from Graphics
renderer: {
type: "simple", // autocasts as new SimpleRenderer()
symbol: {
type: "simple-fill", // autocasts as new SimpleFillSymbol()
color: {r: 200, g: 200, b: 200, a: 0.5},
outline: { // autocasts as new SimpleLineSymbol()
width: 0.5,
color: "black"
}
}
}
});
mapView.map.add(layer);
return layer;
};
});

In ArcGis Js 4.x version you have to also declare a view constructor (MapView for 2D or SceneView for 3D). Here is a guide on how to set up 2D view: https://developers.arcgis.com/javascript/latest/sample-code/intro-mapview/index.html
Another way to add Json file is to convert your existing your json file to an esri json format, like in this guide: https://developers.arcgis.com/javascript/latest/sample-code/sandbox/index.html?sample=layers-featurelayer-collection.
Since I don't know your json file attributes I can't really provide a working sample, but its really simple.

Related

How can I insert the result into a form fiel?

The piece of code bellow (we all know the origin) helps you get geo coordinates.
The result is being displayed in the div called result.
What I need, is for the result to be displayed in a form field so that I can save it to my database, instead of manually typing it.
Thanks
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
The piece of code below (we all know the origin) helps you get geo coordinates.
The result is being displayed in the div called result.
What I need, is for the result to be displayed in a form field so that I can save it to my database, instead of manually typing it.
Thanks

Snazzy Maps in Rails Application

I set up a nice map in my rails application. Everything is working fine but I cannot style the map with SnazzyMaps.
Here is my map.js file:
import GMaps from 'gmaps/gmaps.js';
const mapElement = document.getElementById('map');
if (mapElement) { // don't try to build a map if there's no div#map to inject in
const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
const markers = JSON.parse(mapElement.dataset.markers);
const mapMarkers = map.addMarkers(markers);
mapMarkers.forEach((marker, index) => {
marker.addListener('click', () => {
// map.setCenter(markers[index]);
markers[index].infoWindow.open(map, marker);
})
});
if (markers.length === 0) {
map.setZoom(2);
} else if (markers.length === 1) {
map.setCenter(markers[0].lat, markers[0].lng);
map.setZoom(14);
} else {
map.fitLatLngBounds(markers);
}
}
import { autocomplete } from '../components/autocomplete';
// [...]
autocomplete();
On SnazzyMaps they give the following example. My question is, where shall I insert which part of this code in my own file. Been trying it for a while now but cannot make it work. Here is SnazzyMaps example:
<!DOCTYPE html>
<html>
<head>
<title>Snazzy Maps Super Simple Example</title>
<style type="text/css">
/* Set a size for our map container, the Google Map will take up 100% of this container */
#map {
width: 750px;
height: 500px;
}
</style>
<!--
You need to include this script tag on any page that has a Google Map.
The following script tag will work when opening this example locally on your computer.
But if you use this on a localhost server or a live website you will need to include an API key.
Sign up for one here (it's free for small usage):
https://developers.google.com/maps/documentation/javascript/tutorial#api_key
After you sign up, use the following script tag with YOUR_GOOGLE_API_KEY replaced with your actual key.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY"></script>
-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
function init() {
// Basic options for a simple Google Map
// For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 11,
// The latitude and longitude to center the map (always required)
center: new google.maps.LatLng(40.6700, -73.9400), // New York
// How you would like to style the map.
// This is where you would paste any style found on Snazzy Maps.
styles: [{"featureType":"all","elementType":"geometry.fill","stylers":[{"weight":"2.00"}]},{"featureType":"all","elementType":"geometry.stroke","stylers":[{"color":"#9c9c9c"}]},{"featureType":"all","elementType":"labels.text","stylers":[{"visibility":"on"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"landscape","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"color":"#eeeeee"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#7b7b7b"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#46bcec"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"color":"#c8d7d4"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"color":"#070707"}]},{"featureType":"water","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]}]
};
// Get the HTML DOM element that will contain your map
// We are using a div with id="map" seen below in the <body>
var mapElement = document.getElementById('map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
// Let's also add a marker while we're at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.6700, -73.9400),
map: map,
title: 'Snazzy!'
});
}
</script>
</head>
<body>
<h1>Snazzy Maps Super Simple Example</h1>
<h2>WY</h2>
<!-- The element that will contain our Google Map. This is used in both the Javascript and CSS above. -->
<div id="map"></div>
</body>
</html>
To set the style using Gmaps library, you need to define the styles and then set it to the current map as below:
const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
var styles = [
{
stylers: [
{ hue: "#00ffe6" },
{ saturation: -20 }
]
}, {
featureType: "road",
elementType: "geometry",
stylers: [
{ lightness: 100 },
{ visibility: "simplified" }
]
}, {
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
map.addStyle({
styledMapName:"Styled Map",
styles: styles,
mapTypeId: "map_style"
});
map.setStyle("map_style");
Reference:
https://github.com/hpneo/gmaps/blob/master/examples/styled_maps.html

Graph in popup and separate Div in Leaflet

I wonder if anyone can tell me what is wrong in my code please? I want to be able to select a polygon and show a graph in a popup using leaflet and highchart. I have managed to create the graph in the popup, but the line is missing on it, and I also get a separate div showing the same chart (and the line) at the bottom of my web page which I don't want. Can anyone tell me how to get the line to show on the chart in the popup and to remove the separate chart? Here is my code.enter code here
<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--include leaflet CSS file-->
<link rel="stylesheet" href="css/leaflet.css" />
<link rel="markers" type="images/marker-icon" href="images/marker-icon.png" />
<!--include Leaflet Javascript file-->
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="js/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script src='http://unpkg.com/leaflet#1.0.2/dist/leaflet.js'></script>
<script src="js/esri-leaflet.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
</head>
<body>
<!--Put a div element with a certain id where you want your map to be: -->
<div id="map" style="width: 1000px; height: 800px;"></div>
<div id="chartcontainer" class="highchart" style="width: 500px; height: 200px;"></div>
<!-- First we’ll initialize the map and set its view to our chosen geographical coordinates and a zoom level:-->
<script>
var mymap = L.map('map', {
zoomControl:true, maxZoom:28, minZoom:1
}).fitBounds([[51.0269253989,-1.34762355597],[51.1990603009,-0.951310026203]]);
L.esri.basemapLayer('Imagery').addTo(mymap);
//loads geoserver layer as WMS
var field_boundaries = L.tileLayer.wms("http://localhost:1997/geoserver/RSAC/wms", {
layers: 'RSAC:results_clipped_with_growth_small_new',
format: 'image/png',
transparent: true,
version: '1.1.0',
attribution: "myattribution"
});
//loads the geojson layer
var owsrootUrl = 'http://localhost:1997/geoserver/RSAC/wms';
var defaultParameters = {
service : 'WFS',
version : '2.0',
request : 'GetFeature',
typeName : 'RSAC:results_clipped_with_growth_small_new',
outputFormat : 'json',
format_options : 'callback:getJson',
SrsName : 'EPSG:4326'
};
var parameters = L.Util.extend(defaultParameters);
var URL = owsrootUrl + L.Util.getParamString(parameters);
var ajax = $.ajax({
url : URL,
dataType : 'json',
jsonpCallback : 'getJson',
success : function (response) {
L.geoJson(response, {
onEachFeature: function (feature, url) {
url.on('click', function(e){
var chartplotoptions ={
chart: {
type: 'line'
},
title: {
text: 'Growth'
},
xAxis: {
allowDecimals: true,
categories: ['20151114', '20151126', '20151208', '20151220', '20160113', '20160125', '20160206', '20160218', '20160301', '20160313', '20160325', '20160406', '20160418', '20160430', '20160512', '20160524', '20160605', '20160629', '20160723', '20160804', '20160816'],
labels: {
formatter: function () {
return this.value;
}
}
},
yAxis: {
startOnTick: false,
minPadding: 0.05,
title: {
text: 'Crop Growth',
},
labels: {
formatter: function () {
return this.value;
}
}
},
tooltip: {
pointFormat: '{series.name}{point.y}'
},
plotOptions: {
area: {
pointStart: -20,
threshold: 10,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: false
}
}
}
}
},
series: [{
name: 'Growth',
data: [parseFloat(feature.properties.Date_20151114),parseFloat(feature.properties.Date_20151126),parseFloat(feature.properties.Date_20151208), parseFloat(feature.properties.Date_20151220), parseFloat(feature.properties.Date_20160113), parseFloat(feature.properties.Date_20150125), parseFloat(feature.properties.Date_20160206), parseFloat(feature.properties.Date_20160218), parseFloat(feature.properties.Date_20160301), parseFloat(feature.properties.Date_20160313), parseFloat(feature.properties.Date_20160325), parseFloat(feature.properties.Date_20160406), parseFloat(feature.properties.Date_20160418), parseFloat(feature.properties.Date_20160430), parseFloat(feature.properties.Date_20160512), parseFloat(feature.properties.Date_20160524), parseFloat(feature.properties.Date_20160605), parseFloat(feature.properties.Date_20160629), parseFloat(feature.properties.Date_20160723), parseFloat(feature.properties.Date_20160804), parseFloat(feature.properties.Date_20160816)]
},
]
};
$('#chartcontainer').highcharts(chartplotoptions);
url.bindPopup($('#chartcontainer').html());
url.openPopup();
});
}
}).addTo(mymap);
}
});
</script>
</body>
</html>
You don't need the div element in your HTML markup. You can create one on the fly in your onEachFeature function and add it to the popup. Also, you need to initialize your highchart after the popup has opened, not before. In code with comments:
new L.GeoJSON(feature, {
onEachFeature: function (feature, layer) {
// Create div with class name highchart
var div = L.DomUtil.create('div', 'highchart');
// Bind popup to layer with div as content
layer.bindPopup(div);
// Handle event when popup opens
layer.on('popupopen', function (e) {
console.log(e.target); // layer object
console.log(e.target.feature); // layer's feature object
console.log(e.popup); // popup object
console.log(e.popup.getContent()); // the div
// Now do the highcharts stuff
Highcharts.chart(e.popup.getContent(), { /**/ });
});
}
});
And don't forget to set the div's dimensions with CSS:
.highchart {
width: 500px;
height: 200px;
}

Get Features in heatmap openlayers3

I want to get all features when I click on heat map in openlayers 3...It is possible or not? How to count the features in heat map and give heat map total count features label? thanks
Openlayers3 can do this easily,You can use getFeatures() to get all the features.
var features = heatlayer.getSource().getFeatures()
alert('count: '+features.length);
This method returns an array containing all the features,so you can use length to count.
<!DOCTYPE html>
<html>
<head>
<title>heatlayer count example</title>
<link rel="stylesheet" href="https://openlayers.org/en/v3.20.1/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v3.20.1/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<style>
.map {
max-width: 566px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var heatlayer = new ol.layer.Heatmap({
source: new ol.source.Vector(),
blur: parseInt(14),
radius: parseInt(8)
});
var adddata = [[104.807799,30.232233],[106.803599,31.233225]];
//addfeature
for(var i = 0;i < adddata.length ; i++){
var feature = new ol.Feature({
geometry:new ol.geom.Point([adddata[i][0],adddata[i][1]])
});
heatlayer.getSource().addFeature(feature);
}
var map = new ol.Map({
layers: [raster,heatlayer],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
projection: 'EPSG:4326',
center:[104.07, 30.7],
zoom: 2
})
});
map.on('click', function(event){
var features = heatlayer.getSource().getFeatures()
alert('count: '+features.length);
});
</script>
</body>
</html>

Google Fusion Map Info Window Not Formatted

I have created a Google Fusion Map with 2 layers. All appears to be working correctly with 1 exception.
I have formatted the Info Window of both layers using the Google Fusion Table tool. However, the Info Window on layer 1 is not appearing as specified with the code below. It works fine in the Google Fusion Table tool itself.
Can anyone spot what I've done wrong? Thanks.
<meta charset="UTF-8">
<title>Smithfield Foods UK</title>
<link rel="stylesheet" type="text/css" media="all" href="FusionMapTemplate.css" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var defaultZoom = 10;
var defaultCenter = new google.maps.LatLng(52.6500, 1.2800)
var locationColumn = 'geometry'
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: defaultCenter,
zoom: defaultZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
// Initialize the first layer
var FirstLayer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
},
map: map,
styleId: 3,
templateID: 5,
suppressInfoWindows: true
});
google.maps.event.addListener(FirstLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
// Initialize the second layer
var SecondLayer = new google.maps.FusionTablesLayer({
query: {
select: 'PostCode',
from: '1RrCcRC-1vU0bfHQJTQWqToR-vllSsz9iKnI5WEk'
},
map: map,
styleId: 2,
templateId: 2,
suppressInfoWindows: true
});
google.maps.event.addListener(SecondLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
}
// Open the info window at the clicked location
function windowControl(e, infoWindow, map) {
infoWindow.setOptions({
content: e.infoWindowHtml,
position: e.latLng,
pixelOffset: e.pixelOffset
});
infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
the issue:
templateID: 5,
//-------^
the D has to be lowercase

Resources