Esri / esri-loader

A tiny library to help load ArcGIS API for JavaScript modules in non-Dojo applications
Apache License 2.0
458 stars 79 forks source link

how to use geoJson coordinates array in geometry ? #116

Closed bhumin3i closed 6 years ago

bhumin3i commented 6 years ago

Generate geoJson on map Reference : https://developers.arcgis.com/javascript/latest/sample-code/layers-featurelayer-collection/live/index.html

IN ARCGIS USING THIS GEOJSON FORMATE : https://developers.arcgis.com/javascript/latest/sample-code/layers-featurelayer-collection/live/data/week.geojson

SAMPLE : {"type":"Feature","properties":{"mag":2,"place":"24km WSW of Willow, Alaska","time":1459468945000,"updated":1459469887026,"tz":-480,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/ak13191022","detail":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/ak13191022.geojson","felt":null,"cdi":null,"mmi":null,"alert":null,"status":"automatic","tsunami":0,"sig":62,"net":"ak","code":"13191022","ids":",ak13191022,","sources":",ak,","types":",general-link,geoserve,nearby-cities,origin,tectonic-summary,","nst":null,"dmin":null,"rms":0.55,"gap":null,"magType":"ml","type":"earthquake","title":"M 2.0 - 24km WSW of Willow, Alaska"},"geometry":{"type":"Point","coordinates":[-150.4901,61.6827,49.6]},"id":"ak13191022"}

But in my case i have this .geojson data: when i console : console.log('feature',JSON.stringify(feature)); SAMPLE OBJECT: {"type":"Feature","properties":{"OBJECTID":46,"Shape_Leng":863.321200039,"Shape_Area":43865.4976512,"NAME":"Parking Deck"},"geometry":{"type":"Polygon","coordinates":[[[-78.86322499142115,35.9064166415513,0],[-78.86359030539408,35.906283000714424,0],[-78.86357692404317,35.90625879028665,0],[-78.8636692784858,35.90622500451742,0],[-78.8636826598588,35.906249214935364,0],[-78.86378014504325,35.90621355209226,0],[-78.86411491327716,35.90681922915452,0],[-78.86355975633353,35.90702232009146,0],[-78.86322499142115,35.9064166415513,0]]]}}

how to use array in geometry ?

CODE:

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

import { Platform } from 'ionic-angular';

import { loadModules } from 'esri-loader';
import { Geolocation } from '@ionic-native/geolocation';
import * as crypto from 'crypto-js';

import { AngularEsriModule } from 'angular-esri-components';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage implements OnInit {

  @ViewChild('map') mapEl: ElementRef;
  public mapView: any = null;
  mapMarkerCount:any = 0;
  constructor(public platform: Platform, private geolocation: Geolocation) {

  }

  async  getGeo() {

    // Reference: https://ionicframework.com/docs/api/platform/Platform/#ready
    await this.platform.ready();

    let latitude: number = 0, longitude: number = 0;

    const options = {
      enableHighAccuracy: true, // use any allowed location provider
      timeout: 60000            // it can take quite a while for a cold GPS to warm up
    };
    let watch = this.geolocation.watchPosition(options);
    watch.subscribe((position) => {
      // latitude = position.coords.latitude;
      // longitude = position.coords.longitude;
      latitude = 35.9033;
      longitude = -78.8653;

      // Center map after it has been initialized
      if (this.mapView != null) {
        console.log("Centering map: " + latitude + ", " + longitude);
        this.mapView.center = [longitude, latitude];
      }

    }, error => {

      switch (error.code) {
        case error.PERMISSION_DENIED:
          console.error("User denied the request for Geolocation.");
          break;
        case error.POSITION_UNAVAILABLE:
          console.error("Location information is unavailable.");
          break;
        case error.TIMEOUT:
          console.error("The request to get user location timed out.");
          alert("Unable to start geolocation. Check application settings.");
          break;
      }
    })

    // Load the mapping API modules
    return loadModules([
       "esri/widgets/Track",
      // "esri/widgets/Search",
      'esri/Map',
      'esri/views/MapView',
      "esri/layers/FeatureLayer",
      "esri/geometry/Point",
      "esri/widgets/Legend",
      "esri/request",
      "esri/Graphic",
      "esri/layers/GraphicsLayer",
      "esri/tasks/RouteTask",
      "esri/tasks/support/RouteParameters",
      "esri/tasks/support/FeatureSet",
      "esri/core/urlUtils",
      "esri/widgets/BasemapToggle",
      "dojo/on",
      "dojo/domReady!",

    ]).then(([
      Track,Map, MapView,FeatureLayer,Point, Legend, esriRequest, Graphic, GraphicsLayer, RouteTask, RouteParameters,
      FeatureSet,urlUtils, BasemapToggle, on
      //Search, Track
    ]) => {
      console.log("Geo: starting map");
     var mapMarkerCount = 0;
     var layer, legend;

     /**************************************************
      * Define the specification for each field to create
      * in the layer
      **************************************************/

     var fields = [
     {
       name: "ObjectID",
       alias: "ObjectID",
       type: "oid"
     }, {
       name: "title",
       alias: "title",
       type: "string"
     }, {
       name: "type",
       alias: "type",
       type: "string"
     }, {
       name: "place",
       alias: "place",
       type: "string"
     }, {
       name: "depth",
       alias: "depth",
       type: "string"
     }, {
       name: "time",
       alias: "time",
       type: "date"
     }, {
       name: "mag",
       alias: "Magnitude",
       type: "double"
     }, {
       name: "url",
       alias: "url",
       type: "string"
     }, {
       name: "mmi",
       alias: "intensity",
       type: "double"
     }, {
       name: "felt",
       alias: "Number of felt reports",
       type: "double"
     }, {
       name: "sig",
       alias: "significance",
       type: "double"
     }];

     // Set up popup template for the layer
     var pTemplate = {
       title: "{title}",
       content: [{
         type: "fields",
         fieldInfos: [{
           fieldName: "place",
           label: "Location",
           visible: true
         }, {
           fieldName: "time",
           label: "Date and time",
           visible: true
         }, {
           fieldName: "mag",
           label: "Magnitude",
           visible: true
         }, {
           fieldName: "mmi",
           label: "Intensity",
           visible: true
         }, {
           fieldName: "depth",
           label: "Depth",
           visible: true
         }, {
           fieldName: "felt",
           label: "Number who felt the quake",
           visible: true,
           format: {
             digitSeparator: true,
             places: 0
           }
         }, {
           fieldName: "sig",
           label: "Significance",
           visible: true
         }, {
           fieldName: "url",
           label: "More info",
           visible: true
         }]
       }],
       fieldInfos: [{
         fieldName: "time",
         format: {
           dateFormat: "short-date-short-time"
         }
       }]
     };

     //end var lg

      //new code
      // Proxy the route requests to avoid prompt for log in
      // urlUtils.addProxyRule({
      //   urlPrefix: "route.arcgis.com",
      //   proxyUrl: "http://61.12.113.197:6880/Java/proxy.jsp?"
      // });
      // Point the URL to a valid route service
      var routeTask = new RouteTask({
        url: "https://ehs-gis01.rti.ns/arcgis/rest/services/CampusMap/CampusNeworkAnalysis2/NAServer/Route/"
      });
      // The stops and route result will be stored in this layer
      var routeLyr = new GraphicsLayer();

      // Setup the route parameters
      var routeParams = new RouteParameters({
        stops: new FeatureSet(),
        outSpatialReference: { // autocasts as new SpatialReference()
          wkid: 3857
        }
      });

      // Define the symbology used to display the stops

      var stopSymbol = {
        type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
        style: "cross",
        color: "#124A8A",
        size: 10,
        outline: { // autocasts as new SimpleLineSymbol()
          color: [ 128, 128, 128, 0.5 ],
          width: 1
        }
      };

      // Define the symbology used to display the route
      var routeSymbol = {
        type: "simple-line", // autocasts as SimpleLineSymbol()
        color: [0, 0, 255, 0.5],
        width: 5,
        style: "short-dot"
      };

      //old code
      let map = new Map({
        basemap: "satellite",
        layers: [routeLyr] // Add the route layer to the map
      });

      this.mapView = new MapView({
        // create the map view at the DOM element in this component
        container: this.mapEl.nativeElement,
        center: [35.9033, -78.8653],
        zoom: 15,
        map: map,
        ui: {
          padding: {
            bottom: 15,
            right: 0
          }
        }

      });
      var toggle = new BasemapToggle({
        // 2 - Set properties
        view: this.mapView, // view that provides access to the map's 'topo' basemap
        nextBasemap: "streets" // allows for toggling to the 'hybrid' basemap
      });

      // Add widget to the top right corner of the view
      this.mapView.ui.add(toggle, "top-right");

      on(this.mapView, "click", addStop);
      // this.mapView.ui.add(new Search({
      //   view: this.mapView
      // }), "top-right");
      var track = new Track({
        view: this.mapView
      });
      this.mapView.ui.add(track, "top-left");
      this.mapView.when(function() {
        track.start();
        getData()
        .then(createGraphics) // then send it to the createGraphics() method
        .then(createLayer) // when graphics are created, create the layer
        .then(createLegend) // when layer is created, create the legend
        .catch(errback);
      });

      function addStop(event) {
        console.log('event',event);
        mapMarkerCount = routeParams.stops.features.length;
        console.log('this.mapMarkerCount',mapMarkerCount);
        if(mapMarkerCount == 0){
          stopSymbol.style = "diamond";
        }else{
          stopSymbol.style = "cross";
          stopSymbol.outline.width = 3;
        }

        // Add a point at the location of the map click
        var stop = new Graphic({
          geometry: event.mapPoint,
          symbol: stopSymbol
        });
        routeLyr.add(stop);

        // Execute the route task if 2 or more stops are input
        routeParams.stops.features.push(stop);
         mapMarkerCount = routeParams.stops.features.length;
        console.log('this.mapMarkerCount1',mapMarkerCount);
        if (routeParams.stops.features.length >= 2) {
          routeTask.solve(routeParams).then(showRoute);
        }
      }
      // Adds the solved route to the map as a graphic
      function showRoute(data) {
        var routeResult = data.routeResults[0].route;
        routeResult.symbol = routeSymbol;
        routeLyr.add(routeResult);
      }
        /**************************************************
       * Define the renderer for symbolizing earthquakes
       **************************************************/

      var quakesRenderer = {
        type: "simple", // autocasts as new SimpleRenderer()
        symbol: {
          type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
          style: "circle",
          size: 20,
          color: [211, 255, 0, 0],
          outline: {
            width: 1,
            color: "#FF0055",
            style: "solid"
          }
        },
        visualVariables: [
        {
          type: "size",
          field: "mag", // earthquake magnitude
          valueUnit: "unknown",
          minDataValue: 2,
          maxDataValue: 7,
          // Define size of mag 2 quakes based on scale
          minSize: {
            type: "size",
            valueExpression: "$view.scale",
            stops: [
            {
              value: 1128,
              size: 12
            },
            {
              value: 36111,
              size: 12
            },
            {
              value: 9244649,
              size: 6
            },
            {
              value: 73957191,
              size: 4
            },
            {
              value: 591657528,
              size: 2
            }]
          },
          // Define size of mag 7 quakes based on scale
          maxSize: {
            type: "size",
            valueExpression: "$view.scale",
            stops: [
            {
              value: 1128,
              size: 80
            },
            {
              value: 36111,
              size: 60
            },
            {
              value: 9244649,
              size: 50
            },
            {
              value: 73957191,
              size: 50
            },
            {
              value: 591657528,
              size: 25
            }]
          }
        }]
      };

      // Request the earthquake data
      function getData() {

        // data downloaded from the USGS at http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/ on 4/4/16
        // month.geojson represents recorded earthquakes between 03/04/2016 and 04/04/2016
        // week.geojson represents recorded earthquakes betwen 03/28/2016 and 04/04/2016

        var url = "assets/geojson/week.geojson";

        return esriRequest(url, {
          responseType: "json"
        });
      }

      /**************************************************
       * Create graphics with returned geojson data
       **************************************************/

      function createGraphics(response) {
        // raw GeoJSON data
        var geoJson = response.data;

        // Create an array of Graphics from each GeoJSON feature
        return geoJson.features.map(function(feature, i) {
          console.log('feature',feature);
          return {
            geometry: new Point({
              x: feature.geometry.coordinates[0],
              y: feature.geometry.coordinates[1]
            }),
            // select only the attributes you care about
            attributes: {
              ObjectID: i,
              title: feature.properties.title,
              type: feature.properties.type,
              place: feature.properties.place,
              depth: feature.geometry.coordinates[2] + " km",
              time: feature.properties.time,
              mag: feature.properties.mag,
              mmi: feature.properties.mmi,
              felt: feature.properties.felt,
              sig: feature.properties.sig,
              url: feature.properties.url
            }
          };
        });
      }

      /**************************************************
       * Create a FeatureLayer with the array of graphics
       **************************************************/

      function createLayer(graphics) {

        layer = new FeatureLayer({
          source: graphics, // autocast as an array of esri/Graphic
          // create an instance of esri/layers/support/Field for each field object
          fields: fields, // This is required when creating a layer from Graphics
          objectIdField: "ObjectID", // This must be defined when creating a layer from Graphics
          renderer: quakesRenderer, // set the visualization on the layer
          spatialReference: {
            wkid: 4326
          },
          geometryType: "point", // Must be set when creating a layer from Graphics
          popupTemplate: pTemplate
        });

        map.add(layer);
        return layer;
      }

      /******************************************************************
       * Add layer to layerInfos in the legend
       ******************************************************************/

      function createLegend(layer) {
        // if the legend already exists, then update it with the new layer
        if (legend) {
          legend.layerInfos = [{
            layer: layer,
            title: "Magnitude"
          }];
        } else {

        }
      }

      // Executes if data retrieval was unsuccessful.
      function errback(error) {
        console.error("Creating legend failed. ", error);
      }
    })
      .catch(err => {
        console.log("ArcGIS: " + err);
      });
  }

  ngOnInit() {
    this.getGeo();
  }
}
tomwayson commented 6 years ago

How does this question relate to esri-loader?

bhumin3i commented 6 years ago

@tomwayson sorry i got the solution thanks .