Skip to main content

ArcGIS Javascript API - Pinpoint a Geo-Location by Address

Problem:

I needed a map embedded on a form I was working on to pinpoint a location onto an ArcGIS map.  As far as ArcGIS, there were plenty of examples using latitude and longitude, but no examples using a standard address. This project seemed easier than it really was.

Solution:

I’ve decided to use the Javasript API to solve this problem and it worked like a charm.  Those who are new to ArcGIS should find this post helpful if you want to simply point to a location using an address.  Let’s get right to the code.

Code:

This is just very basic markup to show what files to include and what form elements to use.

HTML (index.html):
<html>
<head>
    <link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/css/esri.css">
    <style>
        html, body, #myMap {
            height: 400px;
            width: 400px;
            margin: 0;
            padding-top: 35px;
        }
    </style>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="https://js.arcgis.com/3.18/"></script>
    <script src="index.js"></script>
</head>
<body>
                <input type="text" id="address" placeholder="address" value="380 New York St." /><br />
                <input type="text" id="city" placeholder="city" value="Redlands"/><br />
                <select id="state">
                                <option value="0" >select state</option>
                                <option value="Alabama">Alabama</option>
                                <option value="California" selected>California</option>
                </select><br />
                <input type="text" id="postalCode" placeholder="postal code" value="92373" /><br />
                <input type="button" id="mapIt" value="Map It!" />

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

JS (index.js):

I wrapped my code in a class so it’s easy to move from one project to another. As you can see, I simply instantiate the class and execute the “init” function.

function LocationMap(){
                var self = this;
                var map;
                
                self.initMap = function(){
                                require(["esri/map"], function(Map){
                                                map = new Map("myMap", {
                                                                basemap: "topo",
                                                                center: [-117.19, 34.05],
                                                                zoom: 13
                                                });                                                           
                                });                           
                }              
                
                self.addAddressToMap = function(fullAddress){
                                require([
                                                "esri/graphic",

                                                "esri/symbols/SimpleMarkerSymbol",
                                                "esri/symbols/TextSymbol",
                                                "esri/symbols/Font",
                                                "esri/tasks/locator",
                                                "dojo/_base/Color",
                                                "dojo/_base/array",

                                                "dojo/dom",
                                                "dojo/on",
                                                "dojo/parser",
                                                "dojo/ready",

                                                "dijit/layout/BorderContainer",
                                                "dijit/layout/ContentPane"],
                                                function (Graphic,
                                                                                  SimpleMarkerSymbol, TextSymbol, Font, Locator,
                                                                                  Color, array,
                                                                                  dom, on, parser, ready,
                                                                                  BorderContainer, ContentPane) {

                                                                ready(function () {

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

                                                                                if(map.graphics){
                                                                                                map.graphics.clear();
                                                                                }

                                                                                locator.addressToLocations({
                                                                                                address: {
                                                                                                                SingleLine: fullAddress
                                                                                                },
                                                                                                outFields: ["Loc_name"]
                                                                                });                           

                                                                                locator.on("address-to-locations-complete", function(candidates){
                                                                                                var symbolMarker = new esri.symbol.PictureMarkerSymbol("https://s3.amazonaws.com/webapps.esri.com/map-pins/Pin_results_17x32.png", 17, 32);
                                                                                                
                                                                                                var candidate = candidates.addresses[0];
                                                                                                
                                                                                                var attributesCandidate = {
                                                                                                                address: candidate.address,
                                                                                                                score: candidate.score,
                                                                                                                locatorName: candidate.attributes.Loc_name
                                                                                                };
                                                                                                var geometryLocation = candidate.location;

                                                                                                var graphicResult = new Graphic(geometryLocation, symbolMarker, attributesCandidate);
                                                                                                map.graphics.add(graphicResult);                                                                                                                            

                                                                                                map.centerAndZoom(geometryLocation, 15);                                     
                                                                                });
                                                                });
                                                });                                           
                }
                
                self.init = function(){
                                self.initMap();   
                                
                                $('#mapIt').click(function(){

                                                var address = $('#address').val();
                                                var city = $('#city').val();
                                                var postalCode = $('#postalCode').val();

                                                if(address && city && postalCode){
                                                                var fullAddress = (address + '. ' + city + ', ' + postalCode);
                                                                self.addAddressToMap(fullAddress);
                                                }              
                                });                           
                                
                }              
                
                return self;
}

$(document).ready(function(){
                var locMap = new LocationMap();
                locMap.init();     
});

Conclusion:

It was hard to find examples of something so simple online, including the ArcGIS sample code online.  I tried to make this a little easier for those interested in learning ArcGIS.

I hope this helps somebody. 



Comments

Popular posts from this blog

Resolved Sitecore "If you publish now, the selected version will not be visible on the web site" warning

The Problem:   Unable to publish any Sitecore item within a particular site, even out of the workflow. Rather, a warning reads " If you publish now, the selected version will not be visible on the web site " What I've Discovered: I couldn't publish any item in the site, not just one or two I viewed all parent items of the items in question The main home page displayed a different warning " This item will never be published because it's publishable option is disabled " Another sitecore developer reminded me of the standard fields option View --> check standard fields to show all standard page fields Found out that somebody checked Never Publish within the publishing section The Fix: After I unchecked the checkbox and saved the change, I was able to publish again.  :) Conclusion: Looks like another Sitecore user thought the children items would not be affected by this change.  Lesson  learned.

[Resolved] Sitecore ParseException: End of string expected at position...

Problem:  I have a line of code that uses Sitecore Fast Query to pull all items + children starting with a site item, like so: Item [] allItems = db.SelectItems( "fast:" + sitecorePath + "//*" ); Unfortunately, I would get a Sitecore parsing error at runtime: ParseException: End of string expected at position... Turns out Sitecore doesn't like hyphens ('-') in any sitecore path when using fast query, which I have a few distributor sites in a folder which contained hyphens. Solution: I create a simple method that resolves a sitecore path to be Sitecore fast query friendly:             string sitecorePath = "" ;             if (siteItem.Paths.FullPath.Contains( "-" ))             {                 String [...

Basic Recursion Example in JavaScript

Problem :  I've been having to write solutions which required some sort of recursion.  The last recursion assignment I had to write was a homework assignment about 10 years ago. I remembered the concept, but forgot how to write it. Solution :  Here’s a simple example of recursion. I start with an array, and after I fire the function, I remove that index from the array, so it shrinks. Once the array is empty, recursion stops.  Pretty straight forward! Code : let books = [ 'Chosen by God', 'Holiness of God', 'Essential Truths', 'Justified by Faith' ]; function readBooks(b){ while (b.length > 0){ console.log('I\'v read ' + b[0]); b.shift(); readBooks(b); } } readBooks(books);