Select to view content in your preferred language

Arcgis map use

4702
2
Jump to solution
01-12-2015 07:26 AM
Thomastso
Deactivated User

Hi everyone,

I am new to arcgis map and  I only know little JavaScript. Could someone please help me with my project?

 

In my project, I want to 1. show current location (same as the following example)

https://developers.arcgis.com/javascript/jssamples/mobile_geolocaterenderer.html

 

AND  2. allow people click on map and pop up address and Latitude&Longitude etc.( same as the following example)

https://developers.arcgis.com/javascript/jssamples/locator_reverse.html

 

I have read though many examples on the Internet BUT I still have no idea what my code should be like to to the above two functions.  I have tried adding some code fragments from example 2 to example 1 but it Does not seems to work.

Please advice.

0 Kudos
1 Solution

Accepted Solutions
JakeSkinner
Esri Esteemed Contributor

Hi Thomas,

Below is an example of the two combined samples.  I started with the GeoLocate sample, and then just added the reverse geocode functionality along with it's required modules:

var locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");

    var infoTemplate = new InfoTemplate("Location", "Address: ${Address}");
    var symbol = new SimpleMarkerSymbol(
      SimpleMarkerSymbol.STYLE_CIRCLE, 
      15, 
      new SimpleLineSymbol(
        SimpleLineSymbol.STYLE_SOLID, 
        new Color([0, 0, 255, 0.5]), 
        8
      ), 
      new Color([0, 0, 255])
    );

    locator.on("location-to-address-complete", function(evt) {
      if (evt.address.address) {
        var address = evt.address.address;
        var location = webMercatorUtils.geographicToWebMercator(evt.address.location);
        //this service returns geocoding results in geographic - convert to web mercator to display on map
        // var location = webMercatorUtils.geographicToWebMercator(evt.location);
        var graphic = new Graphic(location, symbol, address, infoTemplate);
        map.graphics.add(graphic);
        
        map.infoWindow.setTitle(graphic.getTitle());
        map.infoWindow.setContent(graphic.getContent());
        
        //display the info window with the address information
        var screenPnt = map.toScreen(location);
        map.infoWindow.resize(200,100);
        map.infoWindow.show(screenPnt, map.getInfoWindowAnchor(screenPnt));
      }
    });

    map.on("click", function(evt) {
      console.log(evt);
      map.graphics.clear();
      locator.locationToAddress(webMercatorUtils.webMercatorToGeographic(evt.mapPoint), 100);
    });

Full example:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- Sets whether a web application runs in full-screen mode. -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<!-- Sets the style of the status bar for a web application. -->
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>Geolocate</title>

<link rel="stylesheet" href="http://js.arcgis.com/3.12/esri/css/esri.css">
<style>
  html, body {
    height: 100%;
    margin: 0px;
    padding: 0px;
    width: 100%;
  }

  #map {
    height: 100%;
    width: 100%;
  }
</style>

<script src="http://js.arcgis.com/3.12compact/"></script>
<script>
  require([
    "esri/Color",
    "esri/geometry/Point",
    "esri/geometry/webMercatorUtils",
    "esri/graphic",
    "esri/layers/FeatureLayer",
    "esri/map",
    "esri/renderers/SimpleRenderer",
    "esri/renderers/TemporalRenderer",
    "esri/renderers/TimeClassBreaksAger",
    "esri/symbols/SimpleLineSymbol",
    "esri/symbols/SimpleMarkerSymbol",
    "esri/tasks/locator",
    "esri/InfoTemplate",
    "esri/TimeExtent",
    "dojo/domReady!"
  ], function (Color, Point, webMercatorUtils, Graphic, FeatureLayer, Map, SimpleRenderer, TemporalRenderer,
    TimeClassBreaksAger, SimpleLineSymbol, SimpleMarkerSymbol, Locator, InfoTemplate, TimeExtent){

    var map, featureLayer;
    var OBJECTID_COUNTER = 1000;
    var TRACKID_COUNTER = 1;
    //onorientationchange doesn't always fire in a timely manner in Android so check for both orientationchange and resize
    var supportsOrientationChange = "onorientationchange" in window, orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

    window.addEventListener(orientationEvent, function (){
      orientationChanged();
    }, false);

    map = new Map("map", {
      basemap: "streets"
    });
    map.on("load", mapLoadedHandler);
    
    var locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");

    var infoTemplate = new InfoTemplate("Location", "Address: ${Address}");
    var symbol = new SimpleMarkerSymbol(
      SimpleMarkerSymbol.STYLE_CIRCLE, 
      15, 
      new SimpleLineSymbol(
        SimpleLineSymbol.STYLE_SOLID, 
        new Color([0, 0, 255, 0.5]), 
        8
      ), 
      new Color([0, 0, 255])
    );

    locator.on("location-to-address-complete", function(evt) {
      if (evt.address.address) {
        var address = evt.address.address;
        var location = webMercatorUtils.geographicToWebMercator(evt.address.location);
        //this service returns geocoding results in geographic - convert to web mercator to display on map
        // var location = webMercatorUtils.geographicToWebMercator(evt.location);
        var graphic = new Graphic(location, symbol, address, infoTemplate);
        map.graphics.add(graphic);
        
        map.infoWindow.setTitle(graphic.getTitle());
        map.infoWindow.setContent(graphic.getContent());
        
        //display the info window with the address information
        var screenPnt = map.toScreen(location);
        map.infoWindow.resize(200,100);
        map.infoWindow.show(screenPnt, map.getInfoWindowAnchor(screenPnt));
      }
    });

    map.on("click", function(evt) {
      console.log(evt);
      map.graphics.clear();
      locator.locationToAddress(webMercatorUtils.webMercatorToGeographic(evt.mapPoint), 100);
    });


    function mapLoadedHandler(maploadEvent){
      console.log("map loaded", maploadEvent);

      //create a layer definition for the gps points
      var layerDefinition = {
        "objectIdField": "OBJECTID",
        "trackIdField": "TrackID",
        "geometryType": "esriGeometryPoint",
        "timeInfo": {
          "startTimeField": "DATETIME",
          "endTimeField": null,
          "timeExtent": [1277412330365],
          "timeInterval": 1,
          "timeIntervalUnits": "esriTimeUnitsMinutes"
        },
        "fields": [
          {
            "name": "OBJECTID",
            "type": "esriFieldTypeOID",
            "alias": "OBJECTID",
            "sqlType": "sqlTypeOther"
          },
          {
            "name": "TrackID",
            "type": "esriFieldTypeInteger",
            "alias": "TrackID"
          },
          {
            "name": "DATETIME",
            "type": "esriFieldTypeDate",
            "alias": "DATETIME"
          }
        ]
      };

      var featureCollection = {
        layerDefinition: layerDefinition,
        featureSet: null
      };
      featureLayer = new FeatureLayer(featureCollection);

      //setup a temporal renderer
      var sms = new SimpleMarkerSymbol().setColor(new Color([255, 0, 0])).setSize(8);
      var observationRenderer = new SimpleRenderer(sms);
      var latestObservationRenderer = new SimpleRenderer(new SimpleMarkerSymbol());
      var infos = [
        {
          minAge: 0,
          maxAge: 1,
          color: new Color([255, 0, 0])
        }, {
          minAge: 1,
          maxAge: 5,
          color: new Color([255, 153, 0])
        }, {
          minAge: 5,
          maxAge: 10,
          color: new Color([255, 204, 0])
        }, {
          minAge: 10,
          maxAge: Infinity,
          color: new Color([0, 0, 0, 0])
        }
      ];
      var ager = new TimeClassBreaksAger(infos, TimeClassBreaksAger.UNIT_MINUTES);
      var sls = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
        new Color([255, 0, 0]), 3);
      var trackRenderer = new SimpleRenderer(sls);
      var renderer = new TemporalRenderer(observationRenderer, latestObservationRenderer,
        trackRenderer, ager);
      featureLayer.setRenderer(renderer);
      map.addLayer(featureLayer);

      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(zoomToLocation, locationError);
        navigator.geolocation.watchPosition(showLocation, locationError);
      }
    }

    function locationError(error){
      switch (error.code) {
        case error.PERMISSION_DENIED:
          alert("Location not provided");
          break;

        case error.POSITION_UNAVAILABLE:
          alert("Current location not available");
          break;

        case error.TIMEOUT:
          alert("Timeout");
          break;

        default:
          alert("unknown error");
          break;
      }
    }

    function zoomToLocation(location){
      var pt = webMercatorUtils.geographicToWebMercator(new Point(location.coords.longitude,
        location.coords.latitude));
      map.centerAndZoom(pt, 16);
    }

    function showLocation(location){
      if (location.coords.accuracy <= 500) {
        var now = new Date();
        var attributes = {};
        attributes.OBJECTID = OBJECTID_COUNTER;
        attributes.DATETIME = now.getTime();
        attributes.TrackID = TRACKID_COUNTER;

        OBJECTID_COUNTER++;
        TRACKID_COUNTER++;

        var pt = webMercatorUtils.geographicToWebMercator(new Point(location.coords.longitude,
          location.coords.latitude));
        var graphic = new Graphic(new Point(pt, map.spatialReference), null, attributes);

        featureLayer.applyEdits([graphic], null, null, function (adds){
          map.setTimeExtent(new TimeExtent(null, new Date()));
          map.centerAt(graphic.geometry);
        });
      }
      else {
        console.warn("Point not added due to low accuracy: " + location.coords.accuracy);
      }
    }

    function orientationChanged(){
      if (map) {
        map.reposition();
        map.resize();
      }
    }

  });
</script>
</head>

<body>
  <div id="map"></div>
</body>
</html>

View solution in original post

2 Replies
JakeSkinner
Esri Esteemed Contributor

Hi Thomas,

Below is an example of the two combined samples.  I started with the GeoLocate sample, and then just added the reverse geocode functionality along with it's required modules:

var locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");

    var infoTemplate = new InfoTemplate("Location", "Address: ${Address}");
    var symbol = new SimpleMarkerSymbol(
      SimpleMarkerSymbol.STYLE_CIRCLE, 
      15, 
      new SimpleLineSymbol(
        SimpleLineSymbol.STYLE_SOLID, 
        new Color([0, 0, 255, 0.5]), 
        8
      ), 
      new Color([0, 0, 255])
    );

    locator.on("location-to-address-complete", function(evt) {
      if (evt.address.address) {
        var address = evt.address.address;
        var location = webMercatorUtils.geographicToWebMercator(evt.address.location);
        //this service returns geocoding results in geographic - convert to web mercator to display on map
        // var location = webMercatorUtils.geographicToWebMercator(evt.location);
        var graphic = new Graphic(location, symbol, address, infoTemplate);
        map.graphics.add(graphic);
        
        map.infoWindow.setTitle(graphic.getTitle());
        map.infoWindow.setContent(graphic.getContent());
        
        //display the info window with the address information
        var screenPnt = map.toScreen(location);
        map.infoWindow.resize(200,100);
        map.infoWindow.show(screenPnt, map.getInfoWindowAnchor(screenPnt));
      }
    });

    map.on("click", function(evt) {
      console.log(evt);
      map.graphics.clear();
      locator.locationToAddress(webMercatorUtils.webMercatorToGeographic(evt.mapPoint), 100);
    });

Full example:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- Sets whether a web application runs in full-screen mode. -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<!-- Sets the style of the status bar for a web application. -->
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>Geolocate</title>

<link rel="stylesheet" href="http://js.arcgis.com/3.12/esri/css/esri.css">
<style>
  html, body {
    height: 100%;
    margin: 0px;
    padding: 0px;
    width: 100%;
  }

  #map {
    height: 100%;
    width: 100%;
  }
</style>

<script src="http://js.arcgis.com/3.12compact/"></script>
<script>
  require([
    "esri/Color",
    "esri/geometry/Point",
    "esri/geometry/webMercatorUtils",
    "esri/graphic",
    "esri/layers/FeatureLayer",
    "esri/map",
    "esri/renderers/SimpleRenderer",
    "esri/renderers/TemporalRenderer",
    "esri/renderers/TimeClassBreaksAger",
    "esri/symbols/SimpleLineSymbol",
    "esri/symbols/SimpleMarkerSymbol",
    "esri/tasks/locator",
    "esri/InfoTemplate",
    "esri/TimeExtent",
    "dojo/domReady!"
  ], function (Color, Point, webMercatorUtils, Graphic, FeatureLayer, Map, SimpleRenderer, TemporalRenderer,
    TimeClassBreaksAger, SimpleLineSymbol, SimpleMarkerSymbol, Locator, InfoTemplate, TimeExtent){

    var map, featureLayer;
    var OBJECTID_COUNTER = 1000;
    var TRACKID_COUNTER = 1;
    //onorientationchange doesn't always fire in a timely manner in Android so check for both orientationchange and resize
    var supportsOrientationChange = "onorientationchange" in window, orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

    window.addEventListener(orientationEvent, function (){
      orientationChanged();
    }, false);

    map = new Map("map", {
      basemap: "streets"
    });
    map.on("load", mapLoadedHandler);
    
    var locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");

    var infoTemplate = new InfoTemplate("Location", "Address: ${Address}");
    var symbol = new SimpleMarkerSymbol(
      SimpleMarkerSymbol.STYLE_CIRCLE, 
      15, 
      new SimpleLineSymbol(
        SimpleLineSymbol.STYLE_SOLID, 
        new Color([0, 0, 255, 0.5]), 
        8
      ), 
      new Color([0, 0, 255])
    );

    locator.on("location-to-address-complete", function(evt) {
      if (evt.address.address) {
        var address = evt.address.address;
        var location = webMercatorUtils.geographicToWebMercator(evt.address.location);
        //this service returns geocoding results in geographic - convert to web mercator to display on map
        // var location = webMercatorUtils.geographicToWebMercator(evt.location);
        var graphic = new Graphic(location, symbol, address, infoTemplate);
        map.graphics.add(graphic);
        
        map.infoWindow.setTitle(graphic.getTitle());
        map.infoWindow.setContent(graphic.getContent());
        
        //display the info window with the address information
        var screenPnt = map.toScreen(location);
        map.infoWindow.resize(200,100);
        map.infoWindow.show(screenPnt, map.getInfoWindowAnchor(screenPnt));
      }
    });

    map.on("click", function(evt) {
      console.log(evt);
      map.graphics.clear();
      locator.locationToAddress(webMercatorUtils.webMercatorToGeographic(evt.mapPoint), 100);
    });


    function mapLoadedHandler(maploadEvent){
      console.log("map loaded", maploadEvent);

      //create a layer definition for the gps points
      var layerDefinition = {
        "objectIdField": "OBJECTID",
        "trackIdField": "TrackID",
        "geometryType": "esriGeometryPoint",
        "timeInfo": {
          "startTimeField": "DATETIME",
          "endTimeField": null,
          "timeExtent": [1277412330365],
          "timeInterval": 1,
          "timeIntervalUnits": "esriTimeUnitsMinutes"
        },
        "fields": [
          {
            "name": "OBJECTID",
            "type": "esriFieldTypeOID",
            "alias": "OBJECTID",
            "sqlType": "sqlTypeOther"
          },
          {
            "name": "TrackID",
            "type": "esriFieldTypeInteger",
            "alias": "TrackID"
          },
          {
            "name": "DATETIME",
            "type": "esriFieldTypeDate",
            "alias": "DATETIME"
          }
        ]
      };

      var featureCollection = {
        layerDefinition: layerDefinition,
        featureSet: null
      };
      featureLayer = new FeatureLayer(featureCollection);

      //setup a temporal renderer
      var sms = new SimpleMarkerSymbol().setColor(new Color([255, 0, 0])).setSize(8);
      var observationRenderer = new SimpleRenderer(sms);
      var latestObservationRenderer = new SimpleRenderer(new SimpleMarkerSymbol());
      var infos = [
        {
          minAge: 0,
          maxAge: 1,
          color: new Color([255, 0, 0])
        }, {
          minAge: 1,
          maxAge: 5,
          color: new Color([255, 153, 0])
        }, {
          minAge: 5,
          maxAge: 10,
          color: new Color([255, 204, 0])
        }, {
          minAge: 10,
          maxAge: Infinity,
          color: new Color([0, 0, 0, 0])
        }
      ];
      var ager = new TimeClassBreaksAger(infos, TimeClassBreaksAger.UNIT_MINUTES);
      var sls = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
        new Color([255, 0, 0]), 3);
      var trackRenderer = new SimpleRenderer(sls);
      var renderer = new TemporalRenderer(observationRenderer, latestObservationRenderer,
        trackRenderer, ager);
      featureLayer.setRenderer(renderer);
      map.addLayer(featureLayer);

      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(zoomToLocation, locationError);
        navigator.geolocation.watchPosition(showLocation, locationError);
      }
    }

    function locationError(error){
      switch (error.code) {
        case error.PERMISSION_DENIED:
          alert("Location not provided");
          break;

        case error.POSITION_UNAVAILABLE:
          alert("Current location not available");
          break;

        case error.TIMEOUT:
          alert("Timeout");
          break;

        default:
          alert("unknown error");
          break;
      }
    }

    function zoomToLocation(location){
      var pt = webMercatorUtils.geographicToWebMercator(new Point(location.coords.longitude,
        location.coords.latitude));
      map.centerAndZoom(pt, 16);
    }

    function showLocation(location){
      if (location.coords.accuracy <= 500) {
        var now = new Date();
        var attributes = {};
        attributes.OBJECTID = OBJECTID_COUNTER;
        attributes.DATETIME = now.getTime();
        attributes.TrackID = TRACKID_COUNTER;

        OBJECTID_COUNTER++;
        TRACKID_COUNTER++;

        var pt = webMercatorUtils.geographicToWebMercator(new Point(location.coords.longitude,
          location.coords.latitude));
        var graphic = new Graphic(new Point(pt, map.spatialReference), null, attributes);

        featureLayer.applyEdits([graphic], null, null, function (adds){
          map.setTimeExtent(new TimeExtent(null, new Date()));
          map.centerAt(graphic.geometry);
        });
      }
      else {
        console.warn("Point not added due to low accuracy: " + location.coords.accuracy);
      }
    }

    function orientationChanged(){
      if (map) {
        map.reposition();
        map.resize();
      }
    }

  });
</script>
</head>

<body>
  <div id="map"></div>
</body>
</html>
Thomastso
Deactivated User

Thank you very much for your answer.

0 Kudos