Select to view content in your preferred language

How do I pass an address into my javascript API map using URL parameters?

12271
16
Jump to solution
02-18-2015 09:38 AM
GeorgeHaskett
Deactivated User

I am using the latest version of the ESRI JavaScript API to build a basemap template.

 

What I would like to do is pass an address parameter into my map so that when it opens the map is zoomed into the address in question.  I am currently doing this with the Viewer for Flex using the following code:

 

Viewer for Flex: (link not active)     http://myserver.com/flexviewers/actmap/index.html?search=15 Fordham St, Pocatello, Idaho

 

I came across this example for ArcGIS Online:

     http://www.arcgis.com/home/webmap/viewer.html?find=380 new york st,redlands,ca

 

How do I do this with the JavaScript API for ESRI ArcGIS?

Do I need to define parameters within the code or can I simply pass URL parameters to the map like in the above examples to the geocode or locator widgets?

 

Thanks in advance,

0 Kudos
16 Replies
LisCollins
Deactivated User

Thanks so much !

It now works!!

I'm just wondering now why it works. Lol. Do you mind explaining what it's doing?

I wonder why this code works vs the one you mention before below:

  1. // get the URL parameters 
  2.   var params = urlUtils.urlToObject(document.location.href); 
  3.   // check that parameters exist in the URL 
  4.   if (params.query && params.query.address) { 
  5.     var address = params.query.address; 
  6.     map.graphics.clear(); 
  7.     // build address params 
  8.     var addressParams = { 
  9.       "SingleLine": params.query.address 
  10.     }; 
  11.     locator.outSpatialReference = map.spatialReference; 
  12.     var options = { 
  13.       address: addressParams, 
  14.       outFields: ["Loc_name"] 
  15.     }; 
  16.     // send to locator 
  17.     locator.addressToLocations(options);
0 Kudos
ReneRubalcava
Esri Frequent Contributor

That code uses the esri/tasks/locator task to do the address lookup. The Locator task is what powers the Geocoder widget. So in the Geocoder widget (which is on github too) it's doing something very similar to that code.

So it builds address parameters which assume the Geocoder service takes a single line as the address. You set the outSpatialReference so the geocoded results come back in the same spatial reference as the map. And the locator has an addressToLocations method that does the address lookup.

However, the template app already has a Geocoder widget in it, actually it has two for some reason, it also has a mobile it toggles between depending on screen size or device, whatever. So when I saw that, I figured why reinvent the wheel, since you can use the Geocoder find method and select method to get the same result.

Hope that clears it up a bit. Maybe I can do a blog post on this subject too.

Thanks!

LisCollins
Deactivated User

A blog post would be great! I'm surprised this topic is not talked about more. It seems like most web maps could make use of this functionality.

0 Kudos
GeorgeHaskett
Deactivated User

Rene,

I'm still struggling with this one.  I have modified my map code attempting to follow your examples.  I am currently not getting any visual error when the web browser searches for the address, however nothing appears to be happening.  I copied my code and pasted it below.

<!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" />
    <!--The viewport meta tag is used to improve the presentation and behavior of the samples
      on iOS devices-->
    <meta name="viewport"
          content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>PC Map</title>
    <link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css"/>

    <style>
      html, body, #mapDiv {
        padding: 0;
        margin: 0;
        height: 100%;
      }
      #BasemapToggle {
        position: absolute;
        top: 20px;
        right: 70px;
        z-index: 2;
      }
      #search {
        display: block;
        position: absolute;
        z-index: 2;
        top: 20px;
        left: 65px;
      }
      #HomeButton {
        position: absolute;
        z-index: 2;
        top: 95px;
        left: 20px;
        z-index: 50;
      }
      #logo {
        display: block;
        position: absolute;
        top: 16px;
        right: 10px;
        z-index: 3;
        width:45px;
        height:220px;
        background:url(http://fbms2091/flexviewers/_supportDocs/icons/pcLegend_small.png) top right no-repeat;
      }
    </style>
    <script src="http://js.arcgis.com/3.11/"></script>
    <script>
     
      var map, toggle, geocoder, locator;
     
      require([
        "esri/urlUtils",
        "esri/map",
        "esri/dijit/BasemapToggle",
        "esri/dijit/Geocoder",
        "esri/dijit/HomeButton",
        "esri/dijit/Scalebar",
       "esri/graphic",
        "esri/symbols/SimpleMarkerSymbol",
        "esri/symbols/Font",
        "esri/symbols/TextSymbol",
        "dojo/_base/array",
        "esri/geometry/screenUtils",
        "dojo/dom",
        "dojo/dom-construct",
        "dojo/_base/Color",
        "esri/dijit/InfoWindowLite",
        "esri/InfoTemplate",
        "esri/layers/FeatureLayer",
        "dojo/query",
        "esri/tasks/locator",
        "dojo/domReady!"
      ],
     
///Main Map
        function (urlUtils, Map, BasemapToggle, Geocoder, HomeButton, Scalebar, Graphic, SimpleMarkerSymbol, Font, TextSymbol,
  arrayUtils, screenUtils, dom, domConstruct, Color, InfoWindowLite, InfoTemplate, FeatureLayer, query, Locator)
 
  ///Map Frame Extent
        { map = new Map("mapDiv", {
            basemap: "satellite",
            center: [-112.44822, 42.87543],
            zoom: 12
          });
   
      ///Add Basemap Toggle
          toggle = new BasemapToggle({
            map: map,
            basemap: "topo"
          }, "BasemapToggle");
          toggle.startup();
   
      ///Add GeoCoder
          geocoder = new Geocoder({
            arcgisGeocoder: {
              placeholder: "Enter Address"
            },
            autoComplete: true,
            map: map
          }, dom.byId("search"));
          geocoder.startup();
          geocoder.on("select", showLocation);
   
      ///Add HomeButton
          var home = new HomeButton({
            map: map
          }, "HomeButton");
          home.startup();     
         
      ///Add Scalebar
          var scalebar = new Scalebar({
            map: map,
            scalebarUnit: "english"
          });
   
      ///Add Address Location to Map
          function showLocation(evt) {
            map.graphics.clear();
            var point = evt.result.feature.geometry;
            var ptSymbol = new SimpleMarkerSymbol()
              .setStyle("square")
              .setColor(new Color([255,0,0,0.5]));
            var ptGraphic = new Graphic(point, ptSymbol);
            map.graphics.add(ptGraphic);
         
            map.infoWindow.setTitle("Search Result");
            map.infoWindow.setContent(evt.result.name);
            map.infoWindow.show(evt.result.feature.geometry);
          };
   
   ///Popup Window
          var popup = new InfoWindowLite(null, domConstruct.create("div", null, null, map.root));
          popup.startup();
          map.setInfoWindow(popup); 
          var template = new InfoTemplate();
          template.setTitle("<b>FD: ${GRADID} - ${FD_NAME}</b>");
          template.setContent("<p> BUFFER TYPE:  ${BUFFERTYPE} <br/>" + "PC (COM):  ${PC_CF} <br/>" + "PC (PER):  ${PC_DE} <br/>" + "FIRE STATIONS:  ${RESPONDING_FS} <br/>" + "</p>");
   
      ///Add PC Layer to Map
          var featureLayer = new FeatureLayer("http://arcgis.idfbins.com/arcgis/rest/services/FB_ProtectionClass/proClass_cScheme/MapServer/0", {
            mode: FeatureLayer.MODE_ONDEMAND,
            opacity: 0.4,
            infoTemplate:template,
            outFields: ["BUFFERTYPE","GRADID","PC_CF","PC_DE","RESPONDING_FS","FD_NAME"]
          });
          map.addLayer(featureLayer);
          map.popup.resize(200, 75);
   
      ///Set Locator Settings
    locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
    locator.on("address-to-locations-complete", showResults);
   
   ///Get URL Parameters
          map.on("load", function() { 
            // get the URL parameters 
            var params = urlUtils.urlToObject(document.location.href); 
            // check that parameters exist in the URL 
            if (params.query && params.query.address) { 
              var address = params.query.address; 
              map.graphics.clear(); 
              // build address params 
              var addressParams = { 
                "SingleLine": params.query.address 
              }; 
              locator.outSpatialReference = map.spatialReference; 
              var options = { 
                address: addressParams, 
                outFields: ["Loc_name"] 
              }; 
              locator.addressToLocations(options); 
            }
          });
          function locate() {
            map.graphics.clear();
            var address = {
              "SingleLine": dom.byId("address").value
            };
            locator.outSpatialReference = map.spatialReference;
            var options = {
              address: address,
              outFields: ["Loc_name"]
            };
            locator.addressToLocations(options);
          }
   
          function showResults(evt) {
            var symbol = new SimpleMarkerSymbol();
            var infoTemplate = new InfoTemplate(
              "Location",
              "Address: ${address}<br />Score: ${score}<br />Source locator: ${locatorName}"
            );
            symbol.setStyle(SimpleMarkerSymbol.STYLE_SQUARE);
            symbol.setColor(new Color([153,0,51,0.75]));
  
            var geom;
            arrayUtils.every(evt.addresses, function(candidate) {
              console.log(candidate.score);
              if (candidate.score > 80) {
                console.log(candidate.location);
                var attributes = {
                  address: candidate.address,
                  score: candidate.score,
                  locatorName: candidate.attributes.Loc_name
                };  
                geom = candidate.location;
                var graphic = new Graphic(geom, symbol, attributes, infoTemplate);
                //add a graphic to the map at the geocoded location
                map.graphics.add(graphic);
                //add a text symbol to the map listing the location of the matched address.
                var displayText = candidate.address;
                var font = new Font(
                  "14pt",
                  Font.STYLE_NORMAL,
                  Font.VARIANT_NORMAL,
                  Font.WEIGHT_BOLD,
                  "Helvetica"
                );
            
                var textSymbol = new TextSymbol(
                  displayText,
                  font,
                  new Color("#666633")
                );
               textSymbol.setOffset(0,8);
               map.graphics.add(new Graphic(geom, textSymbol));
                return false; //break out of loop after one candidate with score greater  than 80 is found.
              }
            });
            if ( geom !== undefined ) {
              map.centerAndZoom(geom, 12);
            }
          }
  });

    </script>
  </head>
  <body>
    <div id="search"></div>
    <div id="HomeButton"></div>
    <div id="logo"></div>
    <div id="mapDiv"></div>
    <div id="BasemapToggle"></div>
  </body>
</html>

0 Kudos
OwenEarley
Frequent Contributor

Have a look at the reply by Kelly Hutchins in this question - Re: URL coordinate parameters

You can get the URL parameters using urlToObject:

var urlObject = esri.urlToObject(document.location.href);

// check for a URL query and address parameter
if(urlObject.query && urlObject.query.search){ 
  var addr = urlObject.query.search;
  console.log("Address: ", addr);
}

EDIT - Rene just beat me to it and has the correct approach.

ReneRubalcava
Esri Frequent Contributor

I think it's this line.

map.popup.resize(200, 75);

I think what you meant was

map.infoWindow.resize(200, 75);

Once I fixed that, I was able to get the load function to work and it zoomed to an address I passed in the URL.

Hope that helps!

Thanks!

GeorgeHaskett
Deactivated User

Rene, oddly enough I finally got it working by removing the line in question.

Once I removed the following line, everything seemed to work correctly.

  1. map.popup.resize(200, 75); 
0 Kudos