Home

Mapping APIs and Services for Developers

Get Started with the ArcGIS API for JavaScript

Choose a function and see step-by-step how the app is built.

  • <!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">
  • <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
  • <title>Basemaps</title>
  • <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3/js/esri/css/esri.css">
  • <link rel="stylesheet" href="../../css/examples.css">
  • <!-- Load the library references for ArcGIS API for JavaScript -->
  • <script src="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3compact"></script>
  • <script>
  • dojo.require("esri.map");
  • var map;
  • // Create initialization function that sets option for the map
  • function init() {
  • var options = {
  • basemap: "gray",
  • center: [-122.69, 45.52],
  • zoom: 3
  • }
  • // Create map and call Init function
  • map = new esri.Map("mapDiv",options);
  • }
  • dojo.addOnLoad(init);
  • </script>
  • </head>
  • <body>
  • <div class="panel">
  • <div class="titlearea"><span id="titleMessage" class="title-message">Basemaps</span></div>
  • <div class="controls">
  • <div class="buttons">
  • <button class="btn btn-primary btn-wide" onclick="map.setBasemap('streets');">Streets</button>
  • <button class="btn btn-primary btn-wide" onclick="map.setBasemap('satellite');">Satellite</button>
  • <button class="btn btn-primary btn-wide" onclick="map.setBasemap('hybrid');">Hybrid</button>
  • <button class="btn btn-primary btn-wide" onclick="map.setBasemap('topo');">Topo</button>
  • <button class="btn btn-primary btn-wide" onclick="map.setBasemap('gray');">Gray</button>
  • <button class="btn btn-primary btn-wide" onclick="map.setBasemap('national-geographic');">National Geographic</button>
  • </div>
  • </div>
  • <div class="message"><span id="userMessage" class="user-message"></span></div>
  • </div>
  • // Reference the map element
  • <div id="mapDiv"></div>
  • </body>
  • </html>
  • <!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">
  • <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
  • <title>Geolocation</title>
  • <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3/js/esri/css/esri.css" >
  • <link rel="stylesheet" href="../css/examples.css" >
  • <script src="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3compact"></script>
  • <script>
  • dojo.require("esri.map");
  • dojo.require("esri.dijit.Popup");
  • var map;
  • // Set map options and popup window
  • function init() {
  • var options = {
  • basemap: "satellite",
  • center: [-79.40, 43.55],
  • zoom: 9,
  • infoWindow: new esri.dijit.Popup(null, dojo.create("div")) // Define a popup
  • };
  • // Create the map
  • map = new esri.Map("mapDiv",options);
  • autoResize(map);
  • }
  • function showGeolocation() {
  • if (navigator.geolocation){
  • navigator.geolocation.getCurrentPosition(showLocation, errorHandler);
  • setStyle("progress", "progress");
  • } else {
  • alert("Sorry, your browser doesn't support geolocation.");
  • }
  • }
  • function showLocation(position) {
  • // Create a point
  • var pt = new esri.geometry.Point(position.coords.longitude,position.coords.latitude);
  • // Create a symbol and pop-up template. Add the graphic to the map
  • var symbol = createPictureSymbol("http://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png", 4, 9, 28);
  • var attributes = {"lat":pt.y.toFixed(2),"lon":pt.x.toFixed(2)};
  • var infoTemplate = new esri.InfoTemplate("My Location","Latitude: ${lat} <br/>Longitude: ${lon}");
  • var graphic = new esri.Graphic(pt,symbol,attributes,infoTemplate);
  • map.graphics.add(graphic);
  • // Position the center of the map and set zoom level
  • map.centerAndZoom(pt,13);
  • setStyle("progress", "progress hidden");
  • }
  • function errorHandler(err) {
  • setStyle("progress", "progress hidden");
  • if(err.code == 1) {
  • alert("Error: Access is denied!");
  • } else if ( err.code == 2) {
  • alert("Error: Position is unavailable!");
  • } else
  • alert("Error: " + err);
  • }
  • function createPictureSymbol(url, xOffset, yOffset, size) {
  • return new esri.symbol.PictureMarkerSymbol(
  • {
  • "angle": 0,
  • "xoffset": xOffset, "yoffset": yOffset, "type": "esriPMS",
  • "url": url,
  • "contentType": "image/png",
  • "width":size, "height": size
  • });
  • }
  • function clearGeolocationGraphics() {
  • map.infoWindow.hide();
  • map.graphics.clear();
  • }
  • function setStyle(elementName, className) {
  • var element = document.getElementById(elementName);
  • if (element)
  • element.className = className;
  • }
  • function autoResize(map) {
  • dojo.connect(map, 'onLoad', function (map) {
  • dojo.connect(window, 'resize', map, map.resize);
  • });
  • dojo.connect(map, 'onResize', function(extent, width, height) {
  • map.__resizeCenter = map.extent.getCenter();
  • setTimeout(function() {
  • map.centerAt(map.__resizeCenter);
  • }, 200);
  • });
  • }
  • dojo.addOnLoad(init);
  • </script>
  • </head>
  • <body>
  • <div class="message"><span id="userMessage" class="user-message">Find your web browser geolocation</span></div>
  • <div class="panel">
  • <div class="controls">
  • <div class="buttons">
  • <button class="btn btn-primary btn-wide" onclick="showGeolocation();">Find Me</button>
  • </div>
  • </div>
  • </div>
  • <div id="mapDiv"></div>
  • <div id="progress" class="progress hidden"></div>
  • </body>
  • </html>
  • <!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">
  • <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
  • <title>Geosearch</title>
  • <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3/js/esri/css/esri.css">
  • <link rel="stylesheet" href="../../css/examples.css">
  • <!-- Load the library references for ArcGIS API for JavaScript -->
  • <script src="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3compact"></script>
  • <script>
  • dojo.require("esri.map");
  • dojo.require("esri.tasks.locator");
  • dojo.require("esri.dijit.Popup");
  • var map;
  • var geocodeService;
  • function init() {
  • var options = {
  • basemap: "gray",
  • center: [-122.69, 45.52],
  • zoom: 3,
  • infoWindow: new esri.dijit.Popup(null, dojo.create("div")) // Define a popup
  • };
  • // Create map
  • map = new esri.Map("mapDiv",options);
  • autoResize(map);
  • // Create geoservice
  • geocodeService = new esri.tasks.Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
  • dojo.connect(geocodeService, "onAddressToLocationsComplete", geocodeResults);
  • dojo.connect(geocodeService, "onError", geocodeError);
  • }
  • // Listen for enter key
  • function placeInput_onKeyPress(e) {
  • if (e.keyCode == 13 || e.keyCode == "13") {
  • geoSearch();
  • }
  • }
  • // Geocode against the user input
  • function geoSearch() {
  • var searchString = document.getElementById('placeInput').value;
  • var boundingBox;
  • if (document.getElementById('useMapExtent').checked)
  • boundingBox = map.extent;
  • // Set geocode options
  • var options = {
  • address:{"SingleLine":searchString},
  • outFields:["Loc_name"],
  • searchExtent: boundingBox
  • }
  • // Execute geosearch
  • geocodeService.addressToLocations(options);
  • setStyle("progress", "progress visible");
  • }
  • // Geocode results
  • function geocodeResults(places) {
  • if (places.length > 0) {
  • clearFindGraphics();
  • // Objects for the graphic
  • var symbol = createPictureSymbol("../../images/blue-pin.png", 0, 10, 24);
  • var place,attributes,infoTemplate,pt,graphic;
  • // Create and add graphics with pop-ups
  • for (var i = 0; i < places.length; i++) {
  • place = places[i];
  • pt = place.location;
  • attributes = { address:place.address, score:place.score, lat:pt.y.toFixed(2), lon:pt.x.toFixed(2) };
  • infoTemplate = new esri.InfoTemplate("Geocode Result","${address}<br/>Latitude: ${lat}<br/>Longitude: ${lon}<br/>Score: ${score}<span class='popupZoom' onclick='zoomToPlace(" + pt.x + "," + pt.y + ",15)';>Zoom To</span>");
  • graphic = new esri.Graphic(pt,symbol,attributes,infoTemplate);
  • map.graphics.add(graphic);
  • }
  • zoomToPlaces(places);
  • } else {
  • alert("Sorry, address or place not found.");
  • }
  • setStyle("progress", "progress hidden");
  • }
  • function geocodeError(errorInfo) {
  • setStyle("progress", "progress hidden");
  • alert("Sorry, place or address not found!");
  • }
  • function createPictureSymbol(url, xOffset, yOffset, size) {
  • return new esri.symbol.PictureMarkerSymbol(
  • {
  • "angle": 0,
  • "xoffset": xOffset, "yoffset": yOffset, "type": "esriPMS",
  • "url": url,
  • "contentType": "image/png",
  • "width":size, "height": size
  • });
  • }
  • function zoomToPlaces(places) {
  • var multiPoint = new esri.geometry.Multipoint();
  • for (var i = 0; i < places.length; i++) {
  • multiPoint.addPoint(places[i].location);
  • }
  • map.setExtent(multiPoint.getExtent().expand(2.0));
  • }
  • function zoomToPlace(lon,lat,scale) {
  • map.centerAndZoom([lon,lat],scale);
  • }
  • function clearFindGraphics() {
  • map.infoWindow.hide();
  • map.graphics.clear();
  • }
  • function setStyle(elementName, className) {
  • var element = document.getElementById(elementName);
  • if (element)
  • element.className = className;
  • }
  • function autoResize(map) {
  • dojo.connect(map, 'onLoad', function (map) {
  • dojo.connect(window, 'resize', map, map.resize);
  • });
  • dojo.connect(map, 'onResize', function(extent, width, height) {
  • map.__resizeCenter = map.extent.getCenter();
  • setTimeout(function() {
  • map.centerAt(map.__resizeCenter);
  • }, 200);
  • });
  • }
  • dojo.addOnLoad(init);
  • </script>
  • </head>
  • <body>
  • <div class="panel">
  • <div class="titlearea"><span id="titleMessage" class="title-message">Find a Place</span></div>
  • <div class="controls">
  • <div class="buttons">
  • <input id="placeInput" class="" onkeypress="placeInput_onKeyPress(event);" type="text" value="San Diego, CA" placeholder="San Diego, CA"/>
  • <label><input id="useMapExtent" type="checkbox"/>Search in map only</label>
  • <button class="btn btn-primary" id="search" onclick="geoSearch(document.getElementById('placeInput').value);">Go</button>
  • <button class="btn" id="clear" onclick="clearFindGraphics();">Clear</button>
  • </div>
  • </div>
  • </div>
  • <div id="mapDiv"></div>
  • <div id="progress" class="progress hidden"></div>
  • </body>
  • </html>
  • <!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">
  • <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
  • <title>Directions</title>
  • <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3/js/esri/css/esri.css">
  • <link rel="stylesheet" href="../../css/examples.css">
  • <!-- Load the library references for ArcGIS API for JavaScript -->
  • <script src="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3compact"></script>
  • <script>
  • dojo.require("esri.map");
  • dojo.require("esri.dijit.Popup");
  • dojo.require("esri.tasks.locator");
  • dojo.require("esri.tasks.route");
  • dojo.require("dojo.DeferredList");
  • var map;
  • var geocodeService;
  • var directionsService;
  • var directions;
  • var directionsList;
  • var segmentGraphic;
  • function init() {
  • var options = {
  • basemap: "streets",
  • center: [-117, 34],
  • zoom: 5,
  • infoWindow: new esri.dijit.Popup(null, dojo.create("div")) // Define a popup
  • };
  • // Create the map
  • map = new esri.Map("mapDiv",options);
  • autoResize(map);
  • // Create geocode service
  • geocodeService = new esri.tasks.Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
  • dojo.connect(geocodeService, "onError", errorHandler);
  • // Create directions service
  • directionsService = new esri.tasks.RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route");
  • dojo.connect(directionsService, "onSolveComplete", showRoute);
  • dojo.connect(directionsService, "onError", errorHandler);
  • // Container for directions
  • directionsList = document.getElementById('directionsList')
  • }
  • // Find directions for Start and Stop addresses/places
  • function getDirections() {
  • geocodeAddresses();
  • }
  • // Geocode first
  • function geocodeAddresses() {
  • // Geocode address A and B
  • var options = {address:{"SingleLine":document.getElementById('addressInputA').value}};
  • var geocodeAddressACallback = geocodeService.addressToLocations(options);
  • options = {address:{"SingleLine":document.getElementById('addressInputB').value}};
  • var geocodeAddressBCallback = geocodeService.addressToLocations(options);
  • // When A and B come back, create the route
  • var deferredList = new dojo.DeferredList([geocodeAddressACallback,geocodeAddressBCallback]);
  • deferredList.then(calculateDirections);
  • setStyle("progress","progress visible");
  • }
  • // Create route and add graphics
  • function calculateDirections(geocodeResults) {
  • // Get the geocode candidates
  • var start = geocodeResults[0][1][0];
  • var stop = geocodeResults[1][1][0];
  • if (!start || !stop) {
  • setStyle("progress","progress hidden");
  • alert("Sorry, " + (!start ? "Start": "End") + " address not found! Please try again.");
  • return;
  • } else {
  • // Clear old graphics
  • map.graphics.clear();
  • segmentGraphic = null;
  • //Setup the route parameters
  • var routeParams = new esri.tasks.RouteParameters();
  • routeParams.returnRoutes = false;
  • routeParams.returnDirections = true;
  • routeParams.directionsLengthUnits = esri.Units.MILES;
  • routeParams.outSpatialReference = map.spatialReference;
  • routeParams.stops = new esri.tasks.FeatureSet();
  • // Add the graphics to define route stops
  • var startGraphic = addPtGraphic("Start",start);
  • var stopGraphic = addPtGraphic("End",stop);
  • routeParams.stops.features[0] = startGraphic;
  • routeParams.stops.features[1] = stopGraphic;
  • //use the routing task to create a shortest path between those two located address points
  • directionsService.solve(routeParams);
  • }
  • }
  • // Draw the route on the map and show directions
  • function showRoute(routeInfo) {
  • if (routeInfo) {
  • if (routeInfo.routeResults && routeInfo.routeResults.length > 0) {
  • directions = routeInfo.routeResults[0].directions;
  • // Add route to map
  • addLineGraphic(directions.mergedGeometry,[255, 0, 0, 0.5],null,null,true);
  • // Zoom to route
  • map.setExtent(directions.mergedGeometry.getExtent().expand(2.0));
  • // Show turn-by-turn directions
  • showDirections(directions);
  • }
  • }
  • else {
  • alert("Could not find route.");
  • }
  • setStyle("progress", "progress hidden");
  • }
  • function errorHandler(error) {
  • setStyle("progress", "progress hidden");
  • alert("Address not found.");
  • }
  • function addPtGraphic(type,place) {
  • var symbol;
  • if (type == "Start")
  • symbol = createPictureSymbol("../../images/green-pin.png", 0, 10, 24);
  • else
  • symbol = createPictureSymbol("../../images/red-pin.png", 0, 10, 24);
  • // Add graphic to map
  • var attributes = { address:place.address, score:place.score, lat:place.location.y.toFixed(2), lon:place.location.x.toFixed(2) };
  • var infoTemplate = new esri.InfoTemplate(type,"${address}<br/>Latitude: ${lat}<br/>Longitude: ${lon}<br/>Score: ${score}<span class='popupZoom' onclick='zoomToPlace(" + place.location.x.toFixed(2) + "," + place.location.y.toFixed(2) + ",15)';>Zoom To</span>");
  • var graphic = new esri.Graphic(place.location,symbol,attributes,infoTemplate);
  • map.graphics.add(graphic);
  • if (graphic.getDojoShape()){
  • graphic.getDojoShape().moveToFront();
  • }
  • return graphic;
  • }
  • function addLineGraphic(line,color,title,text,moveToBack) {
  • var symbol = new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color(color)).setWidth(4);
  • var infoTemplate;
  • if (title && text)
  • infoTemplate = new esri.InfoTemplate(title,text);
  • var graphic = new esri.Graphic(line,symbol,null,infoTemplate);
  • map.graphics.add(graphic);
  • if (graphic.getDojoShape()){
  • if (graphic && moveToBack)
  • graphic.getDojoShape().moveToBack();
  • else
  • graphic.getDojoShape().moveToFront();
  • }
  • return graphic;
  • }
  • function createPictureSymbol(url, xOffset, yOffset, size) {
  • return new esri.symbol.PictureMarkerSymbol(
  • {
  • "angle": 0,
  • "xoffset": xOffset, "yoffset": yOffset, "type": "esriPMS",
  • "url": url,
  • "contentType": "image/png",
  • "width":size, "height": size
  • });
  • }
  • function zoomToPlace(lon,lat,scale) {
  • map.centerAndZoom([lon,lat],scale);
  • }
  • // Display turn-by-turn directions
  • function showDirections(directions) {
  • var dirStrings = [];
  • for (var i = 0; i < directions.features.length; i++) {
  • var feature = directions.features[i];
  • if (i == 0 || i == directions.length -1)
  • feature.attributes.text = feature.attributes.text;
  • else
  • feature.attributes.text = feature.attributes.text + " (" + feature.attributes.length.toFixed(2) + " miles)";
  • dirStrings.push("<li id=item" + i + " class='info-item' onmouseover='selectDirection(" + i + ",false);' onmousedown='selectDirection(" + i + ",true);'><a>" +feature.attributes.text + "</a></li>");
  • }
  • directionsList.innerHTML = dirStrings.join("");
  • var lbl = document.getElementById("infoTotals");
  • lbl.innerHTML = formatDistance(directions.totalLength, "mile(s)") + " " + formatTime(directions.totalTime);
  • setStyle("infoPanel", "info-panel visible");
  • setStyle("mapDiv","map infoPosition");
  • map.resize();
  • }
  • // Highlight and zoom to route segment
  • function selectDirection(index, zoom) {
  • if (index > -1) {
  • var segment = directions.features[index];
  • var title = "Direction: " + (Number(index) + 1);
  • var text = segment.attributes.text;
  • // Create segment graphic);
  • if (!segmentGraphic) {
  • segmentGraphic = addLineGraphic(segment.geometry,[0, 255, 0, 0.7],title,text,false);
  • } else {
  • segmentGraphic.setGeometry(segment.geometry);
  • }
  • // Show popup
  • map.infoWindow.setTitle(title);
  • map.infoWindow.setContent(text);
  • map.infoWindow.show(segment.geometry.getPoint(0, 0));
  • if (zoom)
  • map.centerAt(segment.geometry.getPoint(0, 0), map.getLevel());
  • }
  • }
  • // Listen for enter key
  • function placeInput_onKeyPress(e) {
  • if (e.keyCode == 13 || e.keyCode == "13") {
  • getDirections();
  • }
  • }
  • //Format the time as hours and minutes
  • function formatTime(time) {
  • var hr = Math.floor(time / 60), //Important to use math.floor with hours
  • min = Math.round(time % 60);
  • if (hr < 1 && min < 1) {
  • return "";
  • }
  • else if (hr < 1) {
  • return min + " min(s)";
  • }
  • return hr + " hr " + min + " min";
  • }
  • //Round the distance to the nearest hundredth of a unit
  • function formatDistance(dist, units) {
  • var d = Math.round(dist * 100) / 100;
  • if (d === 0) {
  • return "";
  • }
  • return d + " " + units;
  • }
  • function clearDirectionGraphics() {
  • setStyle("progress", "progress hidden");
  • setStyle("infoPanel", "info-panel hidden");
  • setStyle("mapDiv","map");
  • map.resize();
  • directionsList.innerHTML = "";
  • map.infoWindow.hide();
  • map.graphics.clear();
  • segmentGraphic = null;
  • }
  • function setMessage(msg) {
  • var element = document.getElementById("message");
  • element.innerHTML = msg;
  • }
  • function setSelected(button) {
  • var elements = document.getElementsByClassName('button');
  • for (var i = 0; i < elements.length; i++) {
  • setStyle(elements[i], "button");
  • }
  • button.className = "button selected";
  • }
  • function setStyle(elementName, className) {
  • var element = document.getElementById(elementName);
  • if (element)
  • element.className = className;
  • }
  • function autoResize(map) {
  • dojo.connect(map, 'onLoad', function (map) {
  • dojo.connect(window, 'resize', map, map.resize);
  • });
  • dojo.connect(map, 'onResize', function(extent, width, height) {
  • map.__resizeCenter = map.extent.getCenter();
  • setTimeout(function() {
  • map.centerAt(map.__resizeCenter);
  • }, 200);
  • });
  • }
  • dojo.addOnLoad(init);
  • </script>
  • </head>
  • <body>
  • <div class="panel">
  • <div class="titlearea"><span id="titleMessage" class="title-message">Directions</span></div>
  • <div class="controls">
  • <div class="buttons">
  • <label>Start:</label> <input id="addressInputA" class="input-medium" onkeypress="placeInput_onKeyPress(event);" type="text" value="Big Bear Lake" placeholder="Big Bear Lake"/></br>
  • <label>End:</label> <input id="addressInputB" class="input-medium" onkeypress="placeInput_onKeyPress(event);" type="text" value="Redlands, CA" placeholder="Redlands, CA"/></br>
  • <button class="btn btn-primary" onclick="getDirections();">Go</button>
  • <button class="btn" onclick="clearDirectionGraphics();">Clear</button>
  • </div>
  • </div>
  • <div id="infoPanel" class="info-panel hidden">
  • <span id="infoLabel" class="info-label">Results:</span>
  • <span id="infoTotals" class="info-totals"></span>
  • <ol id="directionsList" class="info-list"></ol>
  • </div>
  • </div>
  • <div id="mapDiv"></div>
  • <div id="progress" class="progress hidden"></div>
  • </body>
  • </html>
  • <!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">
  • <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
  • <title>Graphics</title>
  • <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3/js/esri/css/esri.css">
  • <link rel="stylesheet" href="../../css/examples.css">
  • <!-- Load the library references for ArcGIS API for JavaScript-->
  • <script src="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3compact"></script>
  • <script>
  • dojo.require("esri.map");
  • dojo.require("esri.dijit.Popup");
  • var map;
  • var pointSymbol,lineSymbol,polygonSymbol;
  • var multiPointGraphic,polylineGraphic,polygonGraphic;
  • var pts, activeToolId;
  • function init() {
  • var options = {
  • basemap: "streets",
  • center: [-79.40, 43.55],
  • zoom: 9,
  • infoWindow: new esri.dijit.Popup(null, dojo.create("div")) // Define a popup
  • };
  • // Create map
  • map = new esri.Map("mapDiv",options);
  • autoResize(map);
  • // Create symbols for the graphics
  • pointSymbol = createPointSymbol();
  • lineSymbol = createLineSymbol();
  • polygonSymbol = createPolygonSymbol();
  • // Connect listeners
  • dojo.connect(map,"onClick", addGraphicCallback);
  • dojo.connect(map,"onDblClick", addGraphicCallback);
  • }
  • function setActiveTool(ctrl) {
  • activeToolId = (ctrl ? ctrl.id : null);
  • // Lock map to digitize
  • if (ctrl) {
  • map.disableDoubleClickZoom();
  • map.disablePan();
  • } else {
  • map.enableDoubleClickZoom();
  • map.enablePan();
  • }
  • // Set user message
  • switch (activeToolId) {
  • case "addPoint":
  • setMessage("Click the map to add a point");
  • break;
  • case "addLine":
  • setMessage("Click the map. Double-click to finish line.");
  • break;
  • case "addPolygon":
  • setMessage("Click the map. Double-click to finish polygon.");
  • break;
  • default:
  • setMessage("Click a button to start");
  • clearAddGraphics();
  • }
  • setSelected(ctrl);
  • }
  • // Listen for mouse click events
  • function addGraphicCallback(evt) {
  • var pt = evt.mapPoint;
  • var finished = (evt.type == "dblclick" || evt.type == "touchend");
  • switch (activeToolId) {
  • case 'addPoint':
  • addPoint(pt, finished);
  • break;
  • case 'addLine':
  • addLine(pt, finished);
  • break;
  • case 'addPolygon':
  • addPolygon(pt, finished);
  • break;
  • default:
  • }
  • }
  • // Add point graphic
  • function addPoint(pt, finished) {
  • var attributes = {"Lat":pt.getLatitude().toFixed(2),"Lon":pt.getLongitude().toFixed(2)};
  • var infoTemplate = new esri.InfoTemplate("My Point","Latitude: ${Lat} <br/>Longitude: ${Lon}");
  • var graphic = new esri.Graphic(pt,pointSymbol,attributes,infoTemplate);
  • map.graphics.add(graphic);
  • }
  • // Add line graphic
  • function addLine(pt, finished) {
  • if (!pts) pts = [];
  • pts.push(pt);
  • // Add a temporary point
  • addTempPoint(pt);
  • // Create the line and graphic
  • if (pts.length > 1) {
  • var polyline = new esri.geometry.Polyline(pt.spatialReference);
  • polyline.addPath(pts);
  • if (!polylineGraphic) {
  • polylineGraphic = new esri.Graphic(polyline,lineSymbol);
  • map.graphics.add(polylineGraphic);
  • } else
  • polylineGraphic.setGeometry(polyline);
  • }
  • if (finished && pts.length > 1) {
  • var infoTemplate = new esri.InfoTemplate("My Line","Points: "+ pts.length);
  • polylineGraphic.setInfoTemplate(infoTemplate);
  • polylineGraphic = null;
  • map.graphics.remove(multiPointGraphic);
  • multiPointGraphic = null;
  • pts = null;
  • }
  • }
  • // Add polygon graphic
  • function addPolygon(pt, finished) {
  • if (!pts) pts = [];
  • pts.push(pt);
  • // Add a temporary point
  • addTempPoint(pt);
  • // Create the polygon and graphic
  • if (pts.length > 1) {
  • if (finished && pts.length > 2)
  • pts.push(pts[0]); // Close the ring
  • var polygon = new esri.geometry.Polygon(pt.spatialReference);
  • polygon.addRing(pts);
  • if (!polygonGraphic) {
  • polygonGraphic = new esri.Graphic(polygon,polygonSymbol);
  • map.graphics.add(polygonGraphic);
  • }
  • else
  • polygonGraphic.setGeometry(polygon);
  • }
  • if (finished && pts.length > 2) {
  • var infoTemplate = new esri.InfoTemplate("My Polygon","Points: " + (pts.length -1));
  • polygonGraphic.setInfoTemplate(infoTemplate);
  • polygonGraphic = null;
  • map.graphics.remove(multiPointGraphic);
  • multiPointGraphic = null;
  • pts = null;
  • }
  • }
  • function addTempPoint(pt) {
  • if (!multiPointGraphic) {
  • multiPoint = new esri.geometry.Multipoint(pt.spatialReference);
  • multiPoint.addPoint(pt);
  • multiPointGraphic = new esri.Graphic(multiPoint,pointSymbol);
  • map.graphics.add(multiPointGraphic);
  • }
  • else {
  • multiPoint.addPoint(pt);
  • multiPointGraphic.setGeometry(multiPoint);
  • }
  • }
  • function createPointSymbol() {
  • return new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 7,
  • new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,
  • new dojo.Color([255, 0, 0]), 1),
  • new dojo.Color([255, 0, 0, 0.75]));
  • }
  • function createLineSymbol() {
  • return new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,
  • new dojo.Color([255, 0, 0, 0.75]),
  • 2);
  • }
  • function createPolygonSymbol() {
  • return new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,
  • new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,
  • new dojo.Color([255, 0, 0, 0.75]), 1), new dojo.Color([255, 0, 0, 0.25]));
  • }
  • function clearAddGraphics() {
  • map.infoWindow.hide();
  • map.graphics.clear();
  • multiPointGraphic = null;
  • polylineGraphic = null;
  • polygonGraphic = null;
  • pts = null;
  • }
  • function setMessage(msg) {
  • var element = document.getElementById("userMessage");
  • element.innerHTML = msg;
  • }
  • function setSelected(button) {
  • var elements = document.getElementsByClassName('btn btn-primary');
  • for (var i = 0; i < elements.length; i++) {
  • elements[i].className = "btn btn-primary";
  • }
  • var element = document.getElementsByClassName('btn btn-primary active');
  • if (element)
  • element.className = "btn btn-primary";
  • if (button)
  • button.className = "btn btn-primary active";
  • }
  • function setStyle(elementName, className) {
  • var element = document.getElementById(elementName);
  • if (element)
  • element.className = className;
  • }
  • function autoResize(map) {
  • dojo.connect(map, 'onLoad', function (map) {
  • dojo.connect(window, 'resize', map, map.resize);
  • });
  • dojo.connect(map, 'onResize', function(extent, width, height) {
  • map.__resizeCenter = map.extent.getCenter();
  • setTimeout(function() {
  • map.centerAt(map.__resizeCenter);
  • }, 200);
  • });
  • }
  • dojo.addOnLoad(init);
  • </script>
  • </head>
  • <body>
  • <div class="panel">
  • <div class="titlearea"><span id="titleMessage" class="title-message">Draw Graphics</span></div>
  • <div class="controls">
  • <div class="buttons">
  • <button class="btn btn-primary" id="addPoint" onclick="setActiveTool(this);">Add Point</button>
  • <button class="btn btn-primary" id="addLine" onclick="setActiveTool(this);">Add Line</button>
  • <button class="btn btn-primary" id="addPolygon" onclick="setActiveTool(this);">Add Polygon</button>
  • <button class="btn" id="clear" onclick="setActiveTool(null);">Clear</button>
  • </div>
  • </div>
  • <div class="message"><span id="userMessage" class="user-message"></span></div>
  • </div>
  • <div id="mapDiv"></div>
  • </body>
  • </html>
  • <!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">
  • <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
  • <title>Cloud</title>
  • <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3/js/esri/css/esri.css">
  • <link rel="stylesheet" href="../../css/examples.css">
  • <!-- Load the library references for ArcGIS API for JavaScript -->
  • <script src="http://serverapi.arcgisonline.com/jsapi/arcgis/3.3compact"></script>
  • <script>
  • dojo.require("esri.map");
  • dojo.require("esri.layers.graphics");
  • dojo.require("esri.layers.FeatureLayer");
  • dojo.require("esri.dijit.Popup");
  • var featureLayer;
  • function init() {
  • var options = {
  • basemap: "gray",
  • center: [-28,40],
  • zoom: 3,
  • infoWindow: new esri.dijit.Popup(null, dojo.create("div")) // Define a popup
  • }
  • // Create map
  • map = new esri.Map("mapDiv", options);
  • // Listen for map update events
  • dojo.connect(map,"onUpdateStart",function(){
  • setStyle("progress", "progress");
  • });
  • dojo.connect(map,"onUpdateEnd",function(){
  • setStyle("progress", "progress hidden");
  • });
  • }
  • function AddCities() {
  • if (featureLayer)
  • return;
  • setStyle("progress", "progress");
  • // Create a feature layer that accesses cloud data
  • var infoTemplate = new esri.InfoTemplate("City Info", "Name: ${NAME}</br>Country: ${COUNTRY}</br>Population:${POPULATION}");
  • featureLayer = new esri.layers.FeatureLayer("http://services.arcgis.com/oKgs2tbjK6zwTdvi/arcgis/rest/services/Major_World_Cities/FeatureServer/0", {
  • mode: esri.layers.FeatureLayer.MODE_ONDEMAND,
  • outFields: ["*"],
  • opacity: .90,
  • infoTemplate: infoTemplate
  • });
  • // Setup symbols for layer
  • var symbol = createPictureSymbol("../../images/blue-dot-small.png", 0, 1, 12);
  • featureLayer.renderer = new esri.renderer.SimpleRenderer(symbol);
  • var selectSymbol = createPictureSymbol("../../images/red-dot-small.png", 0, 1, 12);
  • featureLayer.setSelectionSymbol(selectSymbol);
  • // Add cloud layer
  • map.addLayer(featureLayer);
  • // Connect to selection event
  • dojo.connect(featureLayer,"onSelectionComplete", function (features) {
  • var extent;
  • for (var i = 0; i < features.length; i++) {
  • if (!extent)
  • extent = features[i]._extent;
  • else
  • extent.union(features[i]._extent);
  • }
  • if (extent)
  • map.setExtent(extent);
  • setStyle("progress", "progress hidden");
  • });
  • var element = document.getElementById('searchBySQL');
  • element.disabled = false;
  • }
  • // Select features by SQL query
  • function searchBySQL() {
  • if (!featureLayer) {
  • setMessage("Please add the Cities data first!");
  • return;
  • }
  • map.infoWindow.hide();
  • setStyle("progress", "progress");
  • // Select features in the layer
  • var element = document.getElementById('searchBySQL');
  • var sql = element.options[element.selectedIndex].value;
  • var query = new esri.tasks.Query(); // Select by sql
  • query.where = sql;
  • featureLayer.selectFeatures(query, esri.layers.FeatureLayer.SELECTION_NEW);
  • }
  • function clearCloudGraphics() {
  • setStyle("progress", "progress hidden");
  • map.infoWindow.hide();
  • if (featureLayer)
  • map.removeLayer(featureLayer);
  • featureLayer = null;
  • }
  • function createPictureSymbol(url, xOffset, yOffset, size) {
  • return new esri.symbol.PictureMarkerSymbol(
  • {
  • "angle": 0,
  • "xoffset": xOffset, "yoffset": yOffset, "type": "esriPMS",
  • "url": url,
  • "contentType": "image/png",
  • "width":size, "height": size
  • });
  • }
  • function setMessage(msg) {
  • var element = document.getElementById("userMessage");
  • element.innerHTML = msg;
  • }
  • function setStyle(elementName, className) {
  • var element = document.getElementById(elementName);
  • if (element)
  • element.className = className;
  • }
  • dojo.addOnLoad(init);
  • </script>
  • </head>
  • <body>
  • <div class="panel">
  • <div class="titlearea"><span id="titleMessage" class="title-message">Access the ArcGIS Cloud</span></div>
  • <div class="controls">
  • <div class="buttons">
  • <button class="btn btn-primary" id="addData" onclick="AddCities();">Add World Cities</button>
  • <select class="" id="searchBySQL" onchange="searchBySQL();" disabled>
  • <option selected value="1=0">Select by country</option>
  • <option value="COUNTRY = 'US'">COUNTRY = 'US'</option>
  • <option value="COUNTRY = 'Canada'">COUNTRY = 'Canada'</option>
  • <option value="COUNTRY = 'France'">COUNTRY = 'France'</option>
  • <option value="COUNTRY = 'Australia'">COUNTRY = 'Australia'</option>
  • <option value="COUNTRY = 'Brazil'">COUNTRY = 'Brazil'</option>
  • </select>
  • <button class="btn" id="clearCloudGraphics" onclick="clearCloudGraphics();">Clear</button>
  • </div>
  • </div>
  • <div class="message"><span id="userMessage" class="user-message"></span></div>
  • </div>
  • <div id="mapDiv"></div>
  • <div id="progress" class="progress hidden"></div>
  • </body>
  • </html>

Top of page

Contact Us | Privacy | Legal | Site Map