LocateButton works sporadically after combining with main application.

1283
10
Jump to solution
11-20-2014 02:04 PM
ChrisSergent
Regular Contributor III

I have a LocateButton in my application that was working before I added my measurement tool and now it's working sometimes and sometimes not. Is there something I need to do. The Locate button script is near the end of my JavaScript:

<!DOCTYPE html>

<html>

<head>

  <title>Decatur GIS Template</title>

  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="initial-scale=1,maximum-scale=1, user-scalable=no">

  <link rel="stylesheet" href="http://js.arcgis.com/3.11/dijit/themes/soria/soria.css">

  <link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css">

  <style>

    html,

    body,

    #mapDiv {

      padding: 0;

      margin: 0;

      height: 100%;

      width:100%;

    }

   

    #titlePane

            {

                width:240px;

                position:absolute;

                right:20px;

                bottom:50px;

                background-color:White;

                border-color:Black;

                z-index:50;

            }

            .soria  .dijitTitlePaneTitle {

                background: #fff;

                font-weight:600;

                border: none;

                border-bottom:solid 1px #29201A;

                border-top:solid 1px #29201A;

            }

           

            .soria .dijitTitlePaneTitleHover

            {

                background:#eee;

            }

           

            .soria .dijitTitlePaneTitleActive

            {

                background:#808775;

            }

           

            .soria .dijitTitlePaneContentOuter

            {

                border-right: none;

                border-bottom: none;

                border-left: none;

            }

    #HomeButton {

      position: absolute;

      top: 95px;

      left: 20px;

      z-index: 50;

    }

   

    #LocateButton {

      position: absolute;

      top: 140px;

      left: 20px;

      z-index: 50;

    }

   

    #search {

      display:block;

      position:absolute;

      z-index:3;

      top:20px;

      left:75px;

    }

   

    .esriScalebarLine, .esriScalebarMetricLine

    {

        border-color:White;

    }

           

    .esriScalebarLabel, .esriScalebarLineLabel,.esriScalebarSecondNumber, .esriScaleLabelDiv

    {

        text-shadow:-1px -1px 0 #fff, 

            1px -1px 0 #fff,

            -1px 1px 0 #fff,

            1px 1px 0 #fff;

              

    }

   

    @-webkit-keyframes

    pulse

    {

        0%

        {

            opacity:1.0;

        }

        45%

        {

            opacity:.20;

        }

        {

        100%

        {

            opacity:1.0;

        }

    }

    @-moz-keyframes

        pulse

        {

        0%

        {

            opacity:1.0;

        }

        45%

        {

            opacity:.20;

        }

        100%

        {

            opacity:1.0;

        }

        }

             

        #map_graphics_layer {

        -webkit-animation-duration: 3s;

        -webkit-animation-iteration-count: infinite;

        -webkit-animation-name: pulse;

        -moz-animation-duration: 3s;

        -moz-animation-iteration-count: infinite;

        -moz-animation-name: pulse;

    }

   

   

   

  

  </style>

  <script src="http://js.arcgis.com/3.11/"></script>

  <script>

      var map;

      var graphic;

      var currLocation;

      var watchId;

      var pt;

      require(["esri/map", "esri/config",

              "esri/Color",

              "esri/dijit/Geocoder",

              "esri/dijit/HomeButton",

              "esri/dijit/LocateButton",

              "esri/dijit/Measurement",

              "esri/dijit/OverviewMap",

              "esri/dijit/Scalebar",

              "esri/geometry/Extent",

              "esri/geometry/Point",

              "esri/geometry/screenUtils",

              "esri/graphic",

              "esri/layers/ArcGISTiledMapServiceLayer",

              "esri/layers/ArcGISDynamicMapServiceLayer",

              "esri/layers/LayerDrawingOptions",

              "esri/renderers/SimpleRenderer",

              "esri/SnappingManager",

              "esri/sniff",

              "esri/SpatialReference",

              "esri/symbols/SimpleFillSymbol",

              "esri/symbols/SimpleLineSymbol",

              "esri/symbols/SimpleMarkerSymbol",

              "esri/tasks/GeometryService",

              "esri/tasks/ProjectParameters",

              "dojo/dom",

              "dojo/keys",

              "dojo/on",

              "dojo/parser",

              "dojo/query",

              "dojo/_base/Color",

              "dijit/layout/BorderContainer",

              "dijit/layout/ContentPane",

              "dijit/TitlePane",

              "dijit/form/CheckBox",

              "dojo/domReady!"

            ], function (Map, esriConfig, Color, Geocoder,

                         HomeButton, LocateButton, Measurement, OverviewMap, Scalebar, Extent, Point, screenUtils, Graphic,

                         ArgGISTiledMapServiceLayer, ArcGISDynamicMapServiceLayer, LayerDrawingOptions, SimpleRenderer, SnappingManager, has,

                         SpatialReference, SimpleFillSymbol, SimpleLineSymbol, SimpleMarkerSymbol,

                         GeometryService, ProjectParameters, dom, keys, on, parser, query, Color

            ) {

                parser.parse();

                // set custom extent

                var initialExtent = new Extent({

                    "xmin": 777229.03,

                    "ymin": 1133467.92,

                    "xmax": 848340.14,

                    "ymax": 1185634.58,

                    "spatialReference": {

                        "wkid": 3435

                    }

                });

                // create map and set slider style to small

                map = new Map("mapDiv", {

                    showAttribution: false,

                    sliderStyle: "small",

                    extent: initialExtent

                });

                // add imagery

                var tiled = new ArgGISTiledMapServiceLayer("http://maps.decaturil.gov/arcgis/rest/services/Aerial_2014_Tiled/MapServer");

                map.addLayer(tiled);

                // add operational layer

                var operationalLayer = new ArcGISDynamicMapServiceLayer("http://maps.decaturil.gov/arcgis/rest/services/Public/InternetVector/MapServer", {

                    "opacity": 0.5

                });

                map.addLayer(operationalLayer);

                // declare geometry service

                esriConfig.defaults.geometryService = new GeometryService("http://maps.decaturil.gov/arcgis/rest/services/Utilities/Geometry/GeometryServer");

                // begin geocoder

                var geocoder = new Geocoder({

                    arcgisGeocoder: false,

                    geocoders: [{

                        url: "http://maps.decaturil.gov/arcgis/rest/services/Public/WebAddressLocator/GeocodeServer",

                        name: "Web Address Locator",

                        placeholder: "Find address",

                        outFields: "*"

                    }],

                    map: map,

                    autoComplete: true,

                    zoomScale: 600

                }, dom.byId("search"));

                geocoder.startup();

                geocoder.on("select", showGeocodeLocation);

                function showGeocodeLocation(evt) {

                    map.graphics.clear();

                    var point = evt.result.feature.geometry;

                    var symbol = new SimpleMarkerSymbol()

                        .setStyle("square")

                        .setColor([255, 0, 0, 0.5]);

                    var graphic = new Graphic(point, symbol);

                    map.graphics.add(graphic);

                    map.infoWindow.setTitle("Search Result");

                    map.infoWindow.setContent(evt.result.name);

                    map.infoWindow.show(evt.result.feature.geometry);

                    map.infoWindow.on('hide', function () {

                        map.graphics.clear();

                    });

                }

                // end geocoder

                // geolocation functionality starts here

                map.on("load", initFunc);

                function orientationChanged() {

                    if (map) {

                        map.reposition();

                        map.resize();

                    }

                }

                function initFunc(map) {

                    if (navigator.geolocation) {

                        navigator.geolocation.getCurrentPosition(zoomToLocation, locationError);

                        watchId = navigator.geolocation.watchPosition(showLocation, locationError);

                    } else {

                        alert("Browser doesn't support Geolocation. Visit http://caniuse.com to see browser support for the Geolocation API.");

                    }

                }

                function locationError(error) {

                    //error occurred so stop watchPosition

                    if (navigator.geolocation) {

                        navigator.geolocation.clearWatch(watchId);

                    }

                    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 geopt = new Point(location.coords.longitude, location.coords.latitude);

                    var params = new ProjectParameters();

                    params.geometries = [geopt];

                    params.outSR = new SpatialReference(3435);

                    params.transformation = 108190;

                    params.transformForward = true;

                    esriConfig.defaults.geometryService.project(params, function (projectedPoints) {

                        pt = projectedPoints[0];

                        addGraphic(pt);

                        map.centerAndZoom(pt, 12);

                    });

                }

                // WGS_1984_(ITRF00)_To_NAD_1983 uses the WKID of 108190 - information here: http://downloads2.esri.com/support/TechArticles/Geographic_Transformations_10.1.zip

                function showLocation(location) {

                    //zoom to the users location and add a graphic

                    var geopt = new Point(location.coords.longitude, location.coords.latitude);

                    var params = new ProjectParameters();

                    params.geometries = [geopt];

                    params.outSR = new SpatialReference(3435);

                    params.transformation = 108190;

                    params.transformForward = true;

                    esriConfig.defaults.geometryService.project(params, function (projectedPoints) {

                        pt = projectedPoints[0];

                        if (!graphic) {

                            addGraphic(pt);

                        } else { // move the graphic if it already exists

                            graphic.setGeometry(pt);

                        }

                        map.centerAt(pt);

                    });

                }

                function addGraphic(pt) {

                    var symbol = new SimpleMarkerSymbol(

                                    SimpleMarkerSymbol.STYLE_CIRCLE,

                                    12,

                                    new SimpleLineSymbol(

                                      SimpleLineSymbol.STYLE_SOLID,

                                      new Color([210, 105, 30, 0.5]),

                                      8

                                    ),

                                    new Color([210, 105, 30, 0.9])

                                  );

                    graphic = new Graphic(pt, symbol);

                    map.graphics.add(graphic);

                }

                // geolocation functionality ends here

                // add home button to get full extent

                var home = new HomeButton({

                    map: map

                }, "HomeButton");

                home.startup();

               

                // add overview map

                var overviewMapDijit = new OverviewMap({

                    map: map,

                    visible: false

                });

                overviewMapDijit.startup();

                // scalebar

                var scalebar = new Scalebar({

                    map: map,

                    scalebarUnit: "dual"

                });

               

               

                // start measurement tool - the current layer we are measuring is the operational layer

                var layerDrawingOptions = [];

                var layerDrawingOption = new LayerDrawingOptions();

                var sfs = new SimpleFillSymbol(

                                    "solid",

                                    new SimpleLineSymbol("solid", new Color([195, 176, 23]), 2),

                                    null

                                    );

                layerDrawingOption.renderer = new SimpleRenderer(sfs);

                // change 1 to the layer index that you want to modify:

                layerDrawingOptions[1] = layerDrawingOption;

                //dojo.keys.copyKey maps to CTRL on windows and Cmd on Mac., but has wrong code for Chrome on Mac

                var snapManager = map.enableSnapping({

                    snapKey: has("mac") ? keys.META : keys.CTRL

                });

                var layerInfos = [{

                    layer: operationalLayer

                }];

                snapManager.setLayerInfos(layerInfos);

                var measurement = new Measurement({

                    map: map

                }, dom.byId("measurementDiv"));

                measurement.startup();

                // end measurement tool

                // add geolocate button to find the location of the current user

                geoLocate = new LocateButton({

                    map: map,

                    highlightLocation: true,

                    useTracking: true,

                    enableHighAccuracy: true

                }, "LocateButton");

                geoLocate.clearOnTrackingStop = true;

                geoLocate.startup();

            });

  </script>

</head>

<body onorientationchange="orientationChanged() class="soria">

  <div id="mapDiv">

    <div id="HomeButton"></div>

    <div id="LocateButton"></div>

    <div id="search"></div>

    <div id="titlePane" data-dojo-type="dijit/TitlePane" data-dojo-props="title:' Measurement', closeable:false,open:false">

        <div id="measurementDiv"></div>

        <span style="font-size:smaller;padding:5px 5px;">Press <b>CTRL</b> to enable snapping.</span>

    </div>

  </div>

</body>

</html>

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
KellyHutchins
Esri Frequent Contributor

Sure just call the locate method. Here's an example that shows this:

<!DOCTYPE HTML>

<html>

<head>

  <meta charset="utf-8">

  <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">

  <title>Locate Button</title>

  <link rel="stylesheet" type="text/css" href="http://js.arcgis.com/3.11/esri/css/esri.css">

  <style>

    html, body, #map {

      padding:0;

      margin:0;

      height:100%;

    }

    #LocateButton {

      position: absolute;

      top: 95px;

      left: 20px;

      z-index: 50;

    }

  </style>

  <script src="//js.arcgis.com/3.11/"></script>

  <script>

    var map;

    require([

      "esri/map",

      "esri/dijit/LocateButton",

      "dojo/domReady!"

    ], function(

      Map, LocateButton

    )  {

      map = new Map("map", {

        center: [-56.049, 38.485],

        zoom: 3,

        basemap: "streets"

      });

     map.on("load", function(){

      geoLocate = new LocateButton({

        map: map

      }, "LocateButton");

      geoLocate.startup();

      geoLocate.locate();

     });      

    

    });

  </script>

</head>

<body>

  <div id="map" class="map">

    <div id="LocateButton"></div>

  </div>

</body>

</html>

View solution in original post

10 Replies
KellyHutchins
Esri Frequent Contributor

When you say sometimes it doesn't work can you provide more details? Are there any errors? Looks like your app is using both the HTML5 Geolocation capabilities, the navigator.geolocation, portions of your code and also the Locate button. Is there a reason you need both?

0 Kudos
ChrisSergent
Regular Contributor III

When I open my application at maps.decaturil.gov/decaturgis/ (it's only for Macon County in Illinois), it zooms to my current location automatically and that is what we want it to do for field work. If I immediately click on the locate button, it will also display my current location, but if I move the map around or click on the home button again, the locate button will not update to the new location.

There are no errors.

I have both tools in the application as I want the app to first zoom to the users current location for field work and then if the user navigates around on the map while on site, I want them to be able to quickly find their location if needed without losing anything on the map by using the locate button.

0 Kudos
KellyHutchins
Esri Frequent Contributor

In your app  you have the locate button in tracking mode which means it will check for new locations and update the map when necessary. If you click the button again you take it out of tracking mode.

If you pan the map around your physical location doesn't change so the location will not update. Sounds like this is meant to be running in a browser on a mobile device correct? If so you'll want to test it in that same environment. If you run your app on your phone's browser then do something like walk around the block you should see your location update.

ChrisSergent
Regular Contributor III

Yes, this app will be used on a mobile device. I'll try testing it tomorrow. Will the locate button at least stop all tracking then if I press it? Because I don't want the map to zoom in and out when someone moves around unless they want their location updated.

0 Kudos
KellyHutchins
Esri Frequent Contributor

Tracking will change the location as it gets new location info. If you don't want the location to change without users requesting it then set the useTracking value to false. In that case users would need to re-click the locate button to find their new location.

0 Kudos
ChrisSergent
Regular Contributor III

We're going to try that, but one last thing. Is there a way to get the LocateButton to run the current location on startup?

0 Kudos
KellyHutchins
Esri Frequent Contributor

Sure just call the locate method. Here's an example that shows this:

<!DOCTYPE HTML>

<html>

<head>

  <meta charset="utf-8">

  <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">

  <title>Locate Button</title>

  <link rel="stylesheet" type="text/css" href="http://js.arcgis.com/3.11/esri/css/esri.css">

  <style>

    html, body, #map {

      padding:0;

      margin:0;

      height:100%;

    }

    #LocateButton {

      position: absolute;

      top: 95px;

      left: 20px;

      z-index: 50;

    }

  </style>

  <script src="//js.arcgis.com/3.11/"></script>

  <script>

    var map;

    require([

      "esri/map",

      "esri/dijit/LocateButton",

      "dojo/domReady!"

    ], function(

      Map, LocateButton

    )  {

      map = new Map("map", {

        center: [-56.049, 38.485],

        zoom: 3,

        basemap: "streets"

      });

     map.on("load", function(){

      geoLocate = new LocateButton({

        map: map

      }, "LocateButton");

      geoLocate.startup();

      geoLocate.locate();

     });      

    

    });

  </script>

</head>

<body>

  <div id="map" class="map">

    <div id="LocateButton"></div>

  </div>

</body>

</html>

ChrisSergent
Regular Contributor III

Awesome! The app is now doing exactly what I need it to do. Thanks!

0 Kudos
ReneRubalcava
Frequent Contributor

I was trying this out in jsbin Chris and it seems to work.

Decatur GIS Template

Are there particular steps you tried it that it causes some issues? What kind of behavior are you seeing?

I did notice that your orientationChanged method is referenced in your HTML, but it's not available globally.

0 Kudos