var Adoxio = Adoxio || {}; Adoxio.Esri = Adoxio.Esri || { RootStaticUrl: "https://velocity365-dev.azurewebsites.net/Areas/ArcGIS", RootApiUrl: "https://velocity365-dev.azurewebsites.net/ArcGIS/Esri", // RootApiUrl: "https://localhost:44314/Arcgis/Esri", GetEntityName: function () { if ($("[id$='EntityName']").length > 0) { var typeName = $("[id$='EntityName']:first").val(); return typeName; } } } /*Adoxio.Connect = { Url: function () { var scriptElements = document.getElementsByTagName('script'); var thisFile = $.grep(scriptElements, function (e) { return e.src.contains("ArcGIS/Views/Esri/Scripts/portalesri.js"); }); var segments = thisFile[0].src.split("/Areas"); return segments[0]; }() }; Adoxio.Connect.Esri = { RootStaticUrl: Adoxio.Connect.Url + "/Areas/ArcGIS", RootApiUrl: Adoxio.Connect.Url + "/ArcGIS/Esri", PortalPage: { GetEntityName: function () { if ($("[id$='EntityName']").length > 0) { var typeName = $("[id$='EntityName']:first").val(); return typeName; } }, GetMapSection: function () { return $('table[data-name="esri_map_section"]')[0]; }, GetLocationInput: function () { return $("#abs_location1_address1")[0]; } } } $(function () { var mapSection = Adoxio.Connect.Esri.PortalPage.GetMapSection(); // if the section is present, load the map if (mapSection) { $(mapSection).parent().hide(); // todo: identify the location input based on esri settings object // todo: handle differently when location input is a composite field var locationInput = $(Adoxio.Connect.Esri.PortalPage.GetLocationInput()); locationInput.hide() var locationContainer = locationInput.parent(); locationContainer.append("
"); $('head').append(""); initEsriMap("esrimap", false, true); } }); */ $(function () { if ($('table[data-name="esri_map_section"]').length > 0) { $('table[data-name="esri_map_section"] tbody').append("
"); $('head').append(""); initEsriMap("esrimap", false, true); // this is to fix the responsiveness of columns $('.tab-column[style*="width:50%"]').addClass('col-xs-12 col-sm-12 col-md-6 col-lg-6').css('width', ""); } }); function loadMap(sectionId, MapSettings, point) { require([ "esri/tasks/Locator", "esri/Map", "esri/views/MapView", "esri/layers/Layer", "esri/geometry/Point", "esri/symbols/PictureMarkerSymbol", "esri/symbols/SimpleMarkerSymbol", "esri/symbols/SimpleFillSymbol", "esri/symbols/TextSymbol", "esri/symbols/Font", "esri/Graphic", "esri/layers/GraphicsLayer", "esri/widgets/Locate", "esri/widgets/Search", "esri/layers/FeatureLayer", "esri/geometry/Polygon", "esri/geometry/SpatialReference", "dojo/dom", "dojo/number", "dojo/on", "dojo/domReady!" ], function ( Locator, Map, MapView, Layer, Point, PictureMarkerSymbol, SimpleMarkerSymbol, SimpleFillSymbol, TextSymbol, Font, Graphic, GraphicsLayer, Locate, Search, FeatureLayer, Polygon, SpatialReference, dom, number, on) { //console.log("MapSettings", MapSettings); var rangepoints = []; var spatialReference = new SpatialReference({ wkid: MapSettings.map_abs_spatialreference }); // Set up a locator task using the world geocoding service var locatorTask = new Locator({ url: MapSettings.server_abs_geocoderesturl }); // Create the Map var map = new Map({ basemap: MapSettings.map_abs_basemap }); // Create the MapView var view = new MapView({ container: sectionId, map: map, center: new Point(MapSettings.map_abs_longitude, MapSettings.map_abs_latitude, new SpatialReference({ wkid: MapSettings.map_abs_spatialreference })), zoom: MapSettings.map_abs_initialzoom }); var pinSymbol; if (MapSettings.map_abs_pushpinimage != null) { pinSymbol = new PictureMarkerSymbol(MapSettings.map_abs_pushpinimage, MapSettings.map_abs_pushpinheight, MapSettings.map_abs_pushpinwidth); } else { pinSymbol = new SimpleMarkerSymbol({ style: "circle", color: "#337ab7", size: MapSettings.map_abs_pushpinheight + "px" // pixels }); } var boundaryPolygon; if (MapSettings.map_abs_polygonboundary != null) { boundaryPolygon = new Polygon({ hasZ: false, hasM: false, rings: MapSettings.map_abs_polygonboundary, spatialReference: spatialReference }); } /****************************************************** Locate Widget logic ********************************************/ var locateBtn = new Locate({ viewModel: { // autocasts as new LocateViewModel() view: view, // assigns the locate widget to a view goToLocationEnabled: false } }); if (MapSettings.map_abs_enablelocate) { // Add the locate widget to the top left corner of the view view.ui.add(locateBtn, { position: "top-left" }); } locateBtn.on("locate", function (data) { var lat = data.position.coords.latitude; var lon = data.position.coords.longitude; // check polygon boundary before making reverseGeocode call. if (MapSettings.map_abs_polygonboundary != null) { if (!boundaryPolygon.contains(new Point(lon, lat))) { showMessage('Your current location is outside of the polygon boundary.'); var polygonCenter = boundaryPolygon.centroid; view.goTo({ center: polygonCenter, zoom: MapSettings.map_abs_initialzoom }); return; } } reverseGeocode({ X: lon, Y: lat }, function (data) { //console.log(data); map.layers.removeAll(); view.graphics.removeAll(); if (typeof data != 'object') data=JSON.parse(data); if (data.hasOwnProperty("error")) { plotPointOnMap(data.point, "[" + data.point.X + ", " + data.point.Y + "]"); setCrmFormValues(null, data.point.X, data.point.Y); } else { if (inAddressBoundaries(data.address, true)) { plotPointOnMap({ X: data.location.x, Y: data.location.y }, data.address.Address); setCrmFormValues(data.address, data.location.x, data.location.y); } else { // selected point is not in boundary take user back to center of initial point and zoom view.goTo({ center: [MapSettings.map_abs_longitude, MapSettings.map_abs_latitude], zoom: MapSettings.map_abs_initialzoom }); } } }); }); locateBtn.on("locate-error", function () { showMessage('Unable to find your current location.'); }); /****************************************************** Search Widget logic ********************************************/ if (!MapSettings.map_abs_uselocationfieldforsearch) { var searchWidget = new Search({ view: view, popupEnabled: false, resultGraphicEnabled: false, autoNavigate: false, searchQueryParams: { outSpatialReference: MapSettings.map_abs_spatialreference }, }); if (MapSettings.map_abs_enablesearch) { // Add the search widget to the very top left corner of the view view.ui.add(searchWidget, { position: "top-left", index: 0 }); } searchWidget.on("select-result", function (event) { var x = event.result.feature.geometry.x; var y = event.result.feature.geometry.y; var lat = event.result.feature.geometry.latitude; var lon = event.result.feature.geometry.longitude; // check polygon boundary before making reverseGeocode call. if (MapSettings.map_abs_polygonboundary != null) { if (!boundaryPolygon.contains(new Point(lon, lat))) { showMessage("Selected address does not fall within the boundary;"); var polygonCenter = boundaryPolygon.centroid; view.goTo({ center: polygonCenter, zoom: MapSettings.map_abs_initialzoom }); return; } } if (MapSettings.map_abs_enableBoundaryOnSearch) { GeocodeAddress(event.result.name, true, function (data) { //console.log(data); data.candidates[0].attributes['Address'] = data.candidates[0].address.split(",")[0]; data.candidates[0].attributes['CountryCode'] = data.candidates[0].attributes.Country; // console.log(data.candidates[0]); if (inAddressBoundaries(data.candidates[0].attributes)) { plotPointOnMap({ X: data.candidates[0].location.x, Y: data.candidates[0].location.y }, data.candidates[0].attributes.Address); setCrmFormValues(data.candidates[0].attributes, data.candidates[0].location.x, data.candidates[0].location.y) } else { // selected point is not in boundary take user back to center of initial point and zoom view.goTo({ center: [MapSettings.map_abs_longitude, MapSettings.map_abs_latitude], zoom: MapSettings.map_abs_initialzoom }); } }, 1, false); } else { plotPointOnMap({ X: lon, Y: lat, latitude: lat, longitude: lon }, event.result.name.split(',')[0]); } }); } else { $('body').append(''); var search = new Search({ view: view, popupEnabled: false, resultGraphicEnabled: false, autoNavigate: false, searchQueryParams: { outSpatialReference: MapSettings.map_abs_spatialreference }, container: MapSettings.mapping_abs_locationfieldname }); search.on("select-result", function (event) { var x = event.result.feature.geometry.x; var y = event.result.feature.geometry.y; var lat = event.result.feature.geometry.latitude; var lon = event.result.feature.geometry.longitude; // check polygon boundary before making reverseGeocode call. if (MapSettings.map_abs_polygonboundary != null) { if (!boundaryPolygon.contains(new Point(lon, lat))) { showMessage("Selected address does not fall within the boundary;"); var polygonCenter = boundaryPolygon.centroid; view.goTo({ center: polygonCenter, zoom: MapSettings.map_abs_initialzoom }); return; } } if (MapSettings.map_abs_enableBoundaryOnSearch) { GeocodeAddress(event.result.name, true, function (data) { // console.log(data); data.candidates[0].attributes['Address'] = data.candidates[0].address.split(",")[0]; data.candidates[0].attributes['CountryCode'] = data.candidates[0].attributes.Country; // console.log(data.candidates[0]); if (inAddressBoundaries(data.candidates[0].attributes)) { plotPointOnMap({ X: data.candidates[0].location.x, Y: data.candidates[0].location.y }, data.candidates[0].attributes.Address); setCrmFormValues(data.candidates[0].attributes, data.candidates[0].location.x, data.candidates[0].location.y) } else { // selected point is not in boundary take user back to center of initial point and zoom view.goTo({ center: [MapSettings.map_abs_longitude, MapSettings.map_abs_latitude], zoom: MapSettings.map_abs_initialzoom }); } }, 1, false); } else { plotPointOnMap({ X: lon, Y: lat, latitude: lat, longitude: lon }, event.result.name.split(',')[0]); } }); } /******************************************************************* * This click event ..... *******************************************************************/ if (MapSettings.map_abs_enableclickreversegeocode) { view.on("click", function (event) { if ($("#clickToggle").hasClass('on')) { // hides graphic from locateBtn view.graphics.removeAll(); // Get the coordinates of the click on the view var lat = event.mapPoint.latitude; var lon = event.mapPoint.longitude; // check polygon boundary before making reverseGeocode call. if (MapSettings.map_abs_polygonboundary != null) { if (!boundaryPolygon.contains(new Point(lon, lat))) { showMessage("Please plot point within the boundary."); var polygonCenter = boundaryPolygon.centroid; view.goTo({ center: polygonCenter, zoom: MapSettings.map_abs_initialzoom }); return; } } var clickmode = $("#ReverseGeolocationType button.active").attr('data-type'); if (clickmode != "range") { reverseGeocode({ X: lon, Y: lat }, function (data) { // console.log(data); if(typeof data != 'object') data=JSON.parse(data); if (data.hasOwnProperty("error")) { plotPointOnMap(data.point, "[" + data.point.X + ", " + data.point.Y + "]"); setCrmFormValues(null, data.point.X, data.point.Y); } else { if (inAddressBoundaries(data.address)) { plotPointOnMap({ X: data.location.x, Y: data.location.y }, data.address.Address); //console.log(data.address); setCrmFormValues(data.address, data.location.x, data.location.y); } else { // selected point is not in boundary take user back to center of initial point and zoom view.goTo({ center: [MapSettings.map_abs_longitude, MapSettings.map_abs_latitude], zoom: MapSettings.map_abs_initialzoom }); } } }); } else { var point = new Array(lon, lat); //console.log('points', point); rangepoints.push(point); plotPointOnMap({ X: lon, Y: lat }, rangepoints.length); // console.log('onclick ragepoints', rangepoints) } } }); } else { // remove toggle button $("#clickToggle").remove(); } /******************************************************************* * On map loaded ..... *******************************************************************/ view.then(function () { // This function will execute once the promise is resolved addCustomControl(); if (!window.AdoxioData) { window.AdoxioData = {}; } if (MapSettings.map_abs_uselocationfieldforsearch) { $("#" + MapSettings.mapping_abs_locationfieldname + "_input").addClass("form-control text") } // map appearance settings if (!MapSettings.map_abs_showzoombuttons) { view.ui.remove("zoom"); } if (!MapSettings.map_abs_showattribution) { view.ui.remove("attribution"); } else { $("#ReverseGeolocationType, #clickToggle").addClass('showAttribution'); } view.ui.padding = 5; if (!MapSettings.map_abs_allowintersectionaddress) { $("#ReverseGeolocationType button[data-type='intersection']").remove(); } if (!MapSettings.map_abs_allowrangeaddress) { $("#ReverseGeolocationType button[data-type='range']").remove(); } // attach events $("#ReverseGeolocationType #clear").on('click', function () { if (map.layers != null) { map.layers.removeAll(); } rangepoints = []; }); $("#ReverseGeolocationType #done").on('click', function () { if (rangepoints != null) { // we will store the center of the polygon in lat and long fields //console.log("polygon", polygon.centroid); setCrmFormValues(null, rangepoints[0][0], rangepoints[0][1], "range"); drawPolygonOnMap(); } }); try { //console.log('token logic'); // Token logic if (MapSettings.server_abs_enabletoken) { if (MapSettings.server_abs_applicationtoken == null || MapSettings.server_abs_tokenexpiry == null) { getToken(); } else { if (moment().isBefore(moment(MapSettings.server_abs_tokenexpiry))) { console.log('token is valid'); } else { getToken(); } } } } catch (err) { console.log(err); } // make address required try { if ($("#" + MapSettings.mapping_abs_locationfieldname).length > 0) { addRequiredValidators("#" + MapSettings.mapping_abs_locationfieldname); } } catch (er) { console.log(er); } // plot existing point on record var lat, lon, address = null; if ($("#" + MapSettings.mapping_abs_longitudefieldname) != null) lon = $("#" + MapSettings.mapping_abs_longitudefieldname).val(); if ($("#" + MapSettings.mapping_abs_latitudefieldname) != null) lat = $("#" + MapSettings.mapping_abs_latitudefieldname).val(); if ($("#" + MapSettings.mapping_abs_locationfieldname) != null) address = $("#" + MapSettings.mapping_abs_locationfieldname).val(); if (lon && lat) { plotPointOnMap({ X: lon, Y: lat }, address); } else if (/\S/.test(address) && address != null) { if (address.indexOf('Point on Map') > -1) { var pointString = address.substring(address.lastIndexOf("[") + 1, address.lastIndexOf("]")); var points = pointString.split(','); // console.log(points); plotPointOnMap({ X: points[1], Y: points[0] }, "[" + pointString + "]"); } else if (address.indexOf('Area on Map') > -1) { // console.log('in here should only be on load'); var pointsArray = address.substring(address.lastIndexOf("[") + 1, address.lastIndexOf("]")).split(','); // console.log('pointsArray', pointsArray); var polygonRings = []; for (i = 0; i < pointsArray.length; i++) { var point = [parseFloat(pointsArray[i]), parseFloat(pointsArray[i + 1])]; i++; polygonRings.push(point); } // console.log(polygonRings); //var pointsArray = split2DArray(pointsString,"|",","); rangepoints = polygonRings; drawPolygonOnMap(); } else { GeocodeAddress(address, false, function (data) { plotPointOnMap({ X: data.candidates[0].location.x, Y: data.candidates[0].location.y }, data.candidates[0].address.split(',')[0]); // console.log('geocode', data.candidates[0]); }, 1, false); } } else { if (MapSettings.map_abs_geolocationonload) { if (location.protocol == 'https:') { // console.log("locate me!"); locateBtn.locate(); } else { showMessage("Geolocation is only supported on secure(HTTPS) websites."); } } else { view.goTo([MapSettings.map_abs_longitude, MapSettings.map_abs_latitude]); } } // attach field activations if (MapSettings.mapping_abs_geocodeactivationfieldnames != null) { $(MapSettings.mapping_abs_geocodeactivationfieldnames.split(',')).each(function (index, fieldname) { if ($("#" + fieldname) != null) { var eventType = "change"; if (endsWith(fieldname, "composite")) { fieldname = $("#" + fieldname).parent().find(".btn").attr('id'); // popover done button id eventType = "click"; } $('body').on(eventType, "#" + fieldname, function (event) { // console.log(eventType, fieldname); var address = GetAddressFromCRMForm(); GeocodeAddress(address, true, function (data) { // console.log(data); if (data.candidates[0].score == 100) { data.candidates[0].attributes['Address'] = data.candidates[0].address.split(",")[0]; data.candidates[0].attributes['CountryCode'] = data.candidates[0].attributes.Country; // check polygon boundary is valid if (MapSettings.map_abs_polygonboundary != null) { if (!boundaryPolygon.contains(new Point(data.candidates[0].location.x, data.candidates[0].location.y))) { showMessage("Please type an address within the boundary."); var polygonCenter = boundaryPolygon.centroid; view.goTo({ center: polygonCenter, zoom: MapSettings.map_abs_initialzoom }); return; } } if (inAddressBoundaries(data.candidates[0].attributes)) { plotPointOnMap({ X: data.candidates[0].location.x, Y: data.candidates[0].location.y }, data.candidates[0].attributes.Address); setCrmFormValues(data.candidates[0].attributes, data.candidates[0].location.x, data.candidates[0].location.y) } else { // selected point is not in boundary take user back to center of initial point and zoom view.goTo({ center: [MapSettings.map_abs_longitude, MapSettings.map_abs_latitude], zoom: MapSettings.map_abs_initialzoom }); } } else { // we show a modal with candidates // save them for access in callback window.AdoxioData.ModalOptions = data.candidates; var modalcontrols = ""; $(data.candidates).each(function (index, item) { var radio = '
'; modalcontrols += radio; }); if (MapSettings.map_abs_allowunvalidatedaddress) { modalcontrols += '
'; } showModal("Multiple Address Found.", "

We have found multiple matching addresses to your location. Please select the correct or closest one.

", modalcontrols, function (data) { var result = $('#ESRIModal input[name="address"]:checked').val() || null; if (result == -1 || data == 'false') { if (!MapSettings.map_abs_allowunvalidatedaddress) { setCrmFormValues(null, null, null); } $("#ESRIModal").modal('hide'); //$("#ESRIModal").remove(); return; } var choice = window.AdoxioData.ModalOptions[result]; // console.log('we have selected:', choice); window.AdoxioData.ModalOptions = {}; choice.attributes['Address'] = choice.address.split(",")[0]; choice.attributes['CountryCode'] = choice.attributes.Country; // check polygon boundary is valid if (MapSettings.map_abs_polygonboundary != null) { if (!boundaryPolygon.contains(new Point(choice.location.x, choice.location.y))) { showMessage("Please type an address within the boundary."); var polygonCenter = boundaryPolygon.centroid; view.goTo({ center: polygonCenter, zoom: MapSettings.map_abs_initialzoom }); return; } } if (inAddressBoundaries(choice.attributes)) { plotPointOnMap({ X: choice.location.x, Y: choice.location.y }, choice.attributes.Address); setCrmFormValues(choice.attributes, choice.location.x, choice.location.y); } else { // selected point is not in boundary take user back to center of initial point and zoom view.goTo({ center: [MapSettings.map_abs_longitude, MapSettings.map_abs_latitude], zoom: MapSettings.map_abs_initialzoom }); } $("#ESRIModal").modal('hide'); //$("#ESRIModal").remove(); }); } }); }); } }); } }, function (error) { // This function will execute if the promise is rejected due to an error }); /******************************************************************* *Functions *******************************************************************/ var addCustomControl = function () { var css = ''; $('body').append(css); var controls = '
×
'; $("#" + sectionId + " .esri-view-root").append(controls); $("#ReverseGeolocationType button:not(.rangetoolbar)").on('click', function () { $("#ReverseGeolocationType button").removeClass('active'); $(this).addClass("active"); if ($(this).attr('data-type') == "range") { $(".rangetoolbar").fadeIn(); } else { $(".rangetoolbar").fadeOut(); } // console.log($(this).attr('data-type')); }); $('#message .close').on('click', function (e) { e.preventDefault(); $("#message").fadeOut(); }); $('#clickToggle').on('click', function () { if ($(this).hasClass('on')) { $(this).removeClass("on").addClass("off"); $('#ReverseGeolocationType').slideUp(); } else { $(this).removeClass("off").addClass("on"); $('#ReverseGeolocationType').slideDown(); } }); }; var inAddressBoundaries = function (address, isGeolocation) { var message = "Please select an address within "; if (isGeolocation) { message = "Your current location does not fall within "; } var isCompositefield = false; if (MapSettings.mapping_abs_locationfieldname.indexOf('composite') > -1) { isCompositefield = true; } if (MapSettings.map_abs_country != null) { if (MapSettings.map_abs_country.toUpperCase().indexOf(address.CountryCode.toUpperCase()) == -1) { showMessage(message + MapSettings.map_abs_country + ".", MapSettings.mapping_abs_countryfieldname); return false; } } if (MapSettings.map_abs_stateorprovince != null) { if (address.Region.toUpperCase() != MapSettings.map_abs_stateorprovince.toUpperCase()) { showMessage(message + MapSettings.map_abs_stateorprovince + ".", MapSettings.mapping_abs_stateorprovincefieldname); return false; } } if (MapSettings.map_abs_city != null) { if (address.City.toUpperCase() != MapSettings.map_abs_city.toUpperCase()) { showMessage(message + MapSettings.map_abs_city + ".", MapSettings.mapping_abs_cityfieldname); return false; } } if (MapSettings.map_abs_neighborhood != null) { if (address.Neighborhood.toUpperCase() != MapSettings.map_abs_neighborhood.toUpperCase()) { showMessage(message + MapSettings.map_abs_neighborhood + ".", MapSettings.mapping_abs_neighborhoodfieldname); return false; } } if (MapSettings.map_abs_postalcode != null) { if (MapSettings.map_abs_postalcode.toUpperCase().indexOf(address.Postal.toUpperCase()) == -1) { showMessage(message + MapSettings.map_abs_postalcode + ".", MapSettings.mapping_abs_postalcodefieldname); return false; } } return true; }; var drawPolygonOnMap = function () { try { // console.log('drawpolygoneonmap', rangepoints); var gl = new GraphicsLayer(); var polygon = new Polygon({ hasZ: false, hasM: false, rings: rangepoints, spatialReference: { wkid: MapSettings.map_abs_spatialreference } }); // graphical view for polygon var graphic = new Graphic({ geometry: polygon, symbol: new SimpleFillSymbol() }); gl.add(graphic); map.add(gl); //view.goTo({target: polygon, zoom:MapSettings.map_abs_pushpinzoom}); view.goTo({ target: polygon }); rangepoints = []; } catch (err) { console.log(err); } } var plotPointOnMap = function (point, text) { var gl = new GraphicsLayer(); var point = new Point({ x: point.X, y: point.Y, latitude: point.latitude, longitude: point.longitude, spatialReference: spatialReference }); var clickmode = $("#ReverseGeolocationType button.active").attr('data-type'); if (clickmode != "range") { if (map.layers != null) { map.layers.removeAll(); rangepoints = []; } // this graphic is added from the locate button //view.graphics.removeAll(); var symbol = pinSymbol; var pointGraphic = new Graphic(point, symbol); gl.add(pointGraphic); var textSymbol = new TextSymbol({ color: "#337ab7", haloColor: "black", haloSize: "1px", text: text, yoffset: -18, font: { // autocast as esri/symbols/Font size: 9, family: "sans-serif", weight: "bolder" } }); var TextGraphic = new Graphic(point, textSymbol); gl.add(TextGraphic); map.add(gl); if (view.zoom < MapSettings.map_abs_pushpinzoom) { view.goTo({ center: point, zoom: MapSettings.map_abs_pushpinzoom }); } else { view.goTo({ center: point }); } } else { if (rangepoints.length == 1) { if (map.layers != null) { map.layers.removeAll(); } } // plot point with numbers in center for range draw var symbol = new SimpleMarkerSymbol({ style: "square", color: "#ffffff", size: "11px" // pixels }); ; var pointGraphic = new Graphic(point, symbol); gl.add(pointGraphic); var textSymbol = new TextSymbol({ color: "black", haloColor: "black", haloSize: "1px", text: text, yoffset: -3, font: { // autocast as esri/symbols/Font size: 7, family: "sans-serif", weight: "bolder" } }); var TextGraphic = new Graphic(point, textSymbol); gl.add(TextGraphic); map.add(gl); } }; var getToken = function (callback) { if (MapSettings.server_abs_esriserverid != null) { var PortalConnectTokenURL = Adoxio.Esri.RootApiUrl + "/renewtoken/?serverid=" + MapSettings.server_abs_esriserverid; //Get the esri settings values. $.ajax({ type: "GET", url: PortalConnectTokenURL, }).done(function (data, textStatus, jqXHR) { // console.log('data', data); // data = JSON.parse(data.toString()); data["expires"] = new moment().add(data.expires_in, "seconds").format(); // console.log('token', data); MapSettings['server_abs_applicationtoken'] = data.access_token; MapSettings['server_abs_tokenexpiry'] = data.expires; var server = new Object(); server.abs_applicationtoken = data.access_token; server.abs_tokenexpiry = data.expires; if (callback) { callback(); } }).fail(function (jqXHR, textStatus, errorThrown) { //if unsuccessful, generate an error alert message console.log("Request failed: " + textStatus + "\n" + errorThrown); }); } else { console.log("Cannot renew token because of missing settings. Please setup settings for this entity."); } } var GeocodeAddress = function (address, getAllFields, callback, maxLocations, includeToken) { maxLocations = typeof maxLocations !== 'undefined' ? maxLocations : 10; includeToken = typeof includeToken !== 'undefined' ? includeToken : true; var GeocodeUrl = MapSettings.server_abs_geocoderesturl + "f=json&maxLocations=" + maxLocations; // add spatialreference number GeocodeUrl += "&outSR=" + MapSettings.map_abs_spatialreference; GeocodeUrl += "&singleline=" + encodeURIComponent(address.replace(/\n/g, ",")); if (includeToken && MapSettings.server_abs_enabletoken) { GeocodeUrl += "&token=" + MapSettings.server_abs_applicationtoken; } if (getAllFields) { GeocodeUrl += '&outFields=*'; } // console.log(GeocodeUrl); //Get the esri settings values. $.ajax({ type: "GET", url: GeocodeUrl, }).done(function (data, textStatus, jqXHR) { data = JSON.parse(JSON.stringify(data)); if (data.hasOwnProperty("error")) { if (data.error.code != 400) { // Unable to find address for the specified location. if (data.error.code == 498 && MapSettings.server_abs_enabletoken) { // invalid token AjaxCallAgain(this.url, function (data) { if (callback) { callback(data); } }); } } else { // console.log('address geocode error'); return; } } if (callback) { callback(data); } }).fail(function (jqXHR, textStatus, errorThrown) { //if unsuccessful, generate an error alert message console.log("Request failed: " + textStatus + "\n" + errorThrown); }); }; var AjaxCallAgain = function (getURL, callback) { // console.log('ajaxcallagain'); // console.log('ajaxcallagain', getURL); getToken(function () { //var URL = getURL.replace(/token=.*\./, 'token=' + MapSettings.server_abs_applicationtoken); var URL = getURL.replace(/token=([^&]+|.*$)/, 'token=' + MapSettings.server_abs_applicationtoken); // console.log('ajaxcallagain replace', URL); $.ajax({ type: "GET", url: URL, }).done(function (data, textStatus, jqXHR) { data = JSON.parse(JSON.stringify(data)); if (callback) { callback(data); } }).fail(function (jqXHR, textStatus, errorThrown) { //if unsuccessful, generate an error alert message console.log("Request failed: " + textStatus + "\n" + errorThrown); }); }); } var reverseGeocode = function (point, callback, includeToken) { includeToken = typeof includeToken !== 'undefined' ? includeToken : true; // console.log('reverseGeocode'); var reverseGeocodeUrl = MapSettings.server_abs_reversegeocoderesturl + "f=pjson&location=" + point.X + "," + point.Y; // add spatialreference number reverseGeocodeUrl += "&outSR=" + MapSettings.map_abs_spatialreference; if (includeToken && MapSettings.server_abs_enabletoken) { reverseGeocodeUrl += "&token=" + MapSettings.server_abs_applicationtoken; } var reverseGeocodeType = $("#ReverseGeolocationType button.active").attr('data-type'); switch (reverseGeocodeType) { case "range": // this will be v2 where user can select an area/polygon // range will not require reverse geocode break; case "intersection": reverseGeocodeUrl += "&returnIntersection=true"; reverseGeocodeUrl += "&distance=100"; break; default: reverseGeocodeUrl += "&distance=30" break; } // console.log(reverseGeocodeUrl); //Get the esri settings values. $.ajax({ type: "GET", url: reverseGeocodeUrl, }).done(function (data, textStatus, jqXHR) { data = JSON.parse(JSON.stringify(data)); // console.log(data); if (data.hasOwnProperty("error")) { if (data.error.code != 400) //Unable to find address for the specified location. { if (data.error.code == 498 && MapSettings.server_abs_enabletoken) { // invalid/expired token AjaxCallAgain(this.url, function (data) { if (callback) { callback(data); } }); } } else { if (!MapSettings.map_abs_allowpointwithoutaddress) { showMessage('No address was found near your selected point.'); return; } var uri = new URI(this.url); var search = uri.search(true); var point = search['location'].split(","); data['point'] = { X: parseFloat(point[0]).toFixed(6), Y: parseFloat(point[1]).toFixed(6) }; } } if (callback) { callback(data); } }).fail(function (jqXHR, textStatus, errorThrown) { //if unsuccessful, generate an error alert message console.log("Request failed: " + textStatus + "\n" + errorThrown); }); } var showMessage = function (text, crmfieldname, timeout, messageType) { crmfieldname = typeof crmfieldname !== 'undefined' ? crmfieldname : null; timeout = typeof timeout !== 'undefined' ? timeout : 5000; messageType = typeof messageType !== 'undefined' ? messageType : "alert-warning"; $("#message .text").text(text); $("#message").fadeIn(); $("#message").addClass(messageType); if (crmfieldname != null) { if (crmfieldname.indexOf('composite') > -1) { try { setCrmFormValues(null, null, null); } catch (err) {} } else { //try{ //$("#" +crmfieldname).setNotification(text,crmfieldname); //}catch(err){} } } setTimeout(function () { $("#message").fadeOut(); $("#message").removeClass(messageType); $("#message .text").text(''); }, timeout); } var addRequiredValidators = function (field) { //console.log('Page_Validators', Page_Validators); if (typeof(Page_Validators) == 'undefined') { return; } // Create new validator var newValidator = document.createElement('span'); newValidator.style.display = "none"; newValidator.id = field.split("#")[1] + "Validator"; newValidator.controltovalidate = field.split("#")[1]; newValidator.errormessage = "" + $(field + "_label").text() + " is a required field."; newValidator.validationGroup = ""; // Set this if you have set ValidationGroup on the form newValidator.initialvalue = ""; newValidator.evaluationfunction = function () { var value = $(field).val(); if (value == null || value == "" || value === "undefined" || /\S/.test(value) == false) { return false; } else { return true; } } Page_Validators.push(newValidator); $(field + "_label").parent('div').addClass('required'); return newValidator; }; var setCrmFormValues = function (address, lon, lat, type) { type = typeof type !== 'undefined' ? type : null; //console.log('set this address', address); try { var isCompositefield = false; if (MapSettings.mapping_abs_locationfieldname.indexOf('composite') > -1) { isCompositefield = true; } // this will open the popover if (isCompositefield) { if ($("#" + MapSettings.mapping_abs_locationfieldname) != null) $("#" + MapSettings.mapping_abs_locationfieldname).trigger('click'); } if (address) { if ($("#" + MapSettings.mapping_abs_locationfieldname) != null) { $("#" + MapSettings.mapping_abs_locationfieldname).val(address.Match_addr); if (MapSettings.map_abs_uselocationfieldforsearch) { $("#" + MapSettings.mapping_abs_locationfieldname + "_input").val(address.Match_addr); } } // we set the full address in the line1 field as esri does not return data in multiple lines if ($("#" + MapSettings.mapping_abs_line1fieldname) != null) $("#" + MapSettings.mapping_abs_line1fieldname).val(address.Address); if ($("#" + MapSettings.mapping_abs_line2fieldname) != null) $("#" + MapSettings.mapping_abs_line2fieldname).val(null); if ($("#" + MapSettings.mapping_abs_line3fieldname) != null) $("#" + MapSettings.mapping_abs_line3fieldname).val(null); if ($("#" + MapSettings.mapping_abs_cityfieldname) != null) $("#" + MapSettings.mapping_abs_cityfieldname).val(address.City); if ($("#" + MapSettings.mapping_abs_stateorprovincefieldname) != null) $("#" + MapSettings.mapping_abs_stateorprovincefieldname).val(address.Region); if ($("#" + MapSettings.mapping_abs_postalcodefieldname) != null) $("#" + MapSettings.mapping_abs_postalcodefieldname).val(address.Postal); //if($("#" +MapSettings.mapping_abs_postalcodefieldname).val() == null) if ($("#" + MapSettings.mapping_abs_countryfieldname) != null) $("#" + MapSettings.mapping_abs_countryfieldname).val(address.CountryCode); if ($("#" + MapSettings.mapping_abs_longitudefieldname) != null) $("#" + MapSettings.mapping_abs_longitudefieldname).val(lon); if ($("#" + MapSettings.mapping_abs_latitudefieldname) != null) $("#" + MapSettings.mapping_abs_latitudefieldname).val(lat); } else { var pointonmap = null; if (type == "range") { pointonmap = "Area on Map [" + rangepoints.toString() + "]"; } else { if (lon != null && lat != null) { pointonmap = "Point on Map [" + parseFloat(lon).toFixed(6) + ", " + parseFloat(lat).toFixed(6) + "]"; } } if ($("#" + MapSettings.mapping_abs_locationfieldname) != null) { $("#" + MapSettings.mapping_abs_locationfieldname).val(pointonmap); } if ($("#" + MapSettings.mapping_abs_line1fieldname) != null) { if (isCompositefield) { $("#" + MapSettings.mapping_abs_line1fieldname).val(pointonmap); } else { $("#" + MapSettings.mapping_abs_line1fieldname).val(null); } } if ($("#" + MapSettings.mapping_abs_line2fieldname) != null) { $("#" + MapSettings.mapping_abs_line2fieldname).val(null); } if ($("#" + MapSettings.mapping_abs_line3fieldname) != null) $("#" + MapSettings.mapping_abs_line3fieldname).val(null); if ($("#" + MapSettings.mapping_abs_cityfieldname) != null) $("#" + MapSettings.mapping_abs_cityfieldname).val(null); if ($("#" + MapSettings.mapping_abs_stateorprovincefieldname) != null) $("#" + MapSettings.mapping_abs_stateorprovincefieldname).val(null); if ($("#" + MapSettings.mapping_abs_postalcodefieldname) != null) $("#" + MapSettings.mapping_abs_postalcodefieldname).val(null); if ($("#" + MapSettings.mapping_abs_countryfieldname) != null) $("#" + MapSettings.mapping_abs_countryfieldname).val(null); if ($("#" + MapSettings.mapping_abs_longitudefieldname) != null) $("#" + MapSettings.mapping_abs_longitudefieldname).val(lon); if ($("#" + MapSettings.mapping_abs_latitudefieldname) != null) $("#" + MapSettings.mapping_abs_latitudefieldname).val(lat); } // this will close the popover if (isCompositefield) { if ($("#" + MapSettings.mapping_abs_locationfieldname) != null) { $("#" + MapSettings.mapping_abs_locationfieldname).trigger('click'); } // workaround for date not updating properly in the address field so we set here here again. if (address) { var addressText = ""; if (address.Address != null) { addressText += address.Address + "\n"; } if (address.City != null) { addressText += address.City + ", "; } if (address.Region != null) { addressText += address.Region + " "; } if (address.Postal != null) { addressText += address.Postal + "\n"; } addressText += address.CountryCode; $("#" + MapSettings.mapping_abs_locationfieldname).val(addressText); } } } catch (err) { console.log('error', err); } }; var GetAddressFromCRMForm = function () { var address; if ($("#" + MapSettings.mapping_abs_locationfieldname) != null) //$("#" +MapSettings.mapping_abs_locationfieldname).val(); // we set the full address in the line1 field as esri does not return data in multiple lines if ($("#" + MapSettings.mapping_abs_line1fieldname).length > 0) address = $("#" + MapSettings.mapping_abs_line1fieldname).val() + " "; if ($("#" + MapSettings.mapping_abs_line2fieldname).length > 0) address += $("#" + MapSettings.mapping_abs_line2fieldname).val() + " "; if ($("#" + MapSettings.mapping_abs_line3fieldname).length > 0) address += $("#" + MapSettings.mapping_abs_line3fieldname).val() + " "; if ($("#" + MapSettings.mapping_abs_cityfieldname).length > 0) address += ", " + $("#" + MapSettings.mapping_abs_cityfieldname).val() + ", "; if ($("#" + MapSettings.mapping_abs_stateorprovincefieldname).length > 0) address += $("#" + MapSettings.mapping_abs_stateorprovincefieldname).val() + ", "; if ($("#" + MapSettings.mapping_abs_postalcodefieldname).length > 0) address += $("#" + MapSettings.mapping_abs_postalcodefieldname).val() + ", "; if ($("#" + MapSettings.mapping_abs_countryfieldname).length > 0) address += $("#" + MapSettings.mapping_abs_countryfieldname).val() + " "; address = address.replace(/null/g, ""); return address; }; var endsWith = function (str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; } var showModal = function (title, body, controls, callback) { controls = typeof controls !== 'undefined' ? controls : ""; try { $("#ESRIModal").remove(); } catch (er) {} var Modal = ''; $("body").append(Modal); $("#ESRIModal").modal('show'); $("#ESRIModal .modal-footer button").each(function (index, value) { $(this).on("click", function () { console.log($(this).attr('data-value')); if (callback) { callback($(this).attr('data-value')); } }); }); } }); } function initEsriMap(sectionId, scriptsloaded, isPortal) { scriptsloaded = typeof scriptsloaded !== 'undefined' ? scriptsloaded : false; isPortal = typeof isPortal !== 'undefined' ? isPortal : true; if (!scriptsloaded) { var loadScript = function (url, type, callback) { // Adding the script tag to the head as suggested before var head = document.getElementsByTagName('head')[0]; var script; if (type == "js") { script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // Then bind the event to the callback function. // There are several events for cross browser compatibility. script.onreadystatechange = callback; script.onload = callback; } else { script = document.createElement('link'); script.rel = 'stylesheet'; script.type = 'text/css'; script.href = url; } //console.log(script); // Fire the loading head.appendChild(script); }; var esriCSS = "//js.arcgis.com/4.2/esri/css/main.css"; var bootstrapCSS = "//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"; var fontawesomeCSS = "//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"; var jqueryJS = "//ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"; var bootstrapJS = "//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"; var URIJS = "//cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.7/URI.min.js"; var momentJS = "//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"; var esriJS = "https://js.arcgis.com/4.2/"; if (!isPortal) { loadScript(esriCSS, "stylesheet"); loadScript(bootstrapCSS, "stylesheet"); loadScript(fontawesomeCSS, "stylesheet"); loadScript(jqueryJS, "js", function () { loadScript(bootstrapJS, "js"); loadScript(URIJS, "js"); loadScript(momentJS, "js"); loadScript(esriJS, "js"); loadScript(esriJS, "js", function () { initEsriMap(sectionId, true); }); }); } else { loadScript(esriCSS, "stylesheet"); loadScript(fontawesomeCSS, "stylesheet"); loadScript(esriJS, "js", function () { initEsriMap(sectionId, true); }); } } else { var EsriSettings; var GetEsriSettings = function (typeName, callback) { // liquid template rss feed xml return var portalBaseUrl = window.location.origin; var EsriSettingsRSSFeed = "/service-request-map/srm-feed/?settings=true&entitylogicalname=" + typeName var endpointUrl = portalBaseUrl + EsriSettingsRSSFeed; //console.log('endpointUrl', endpointUrl); //Get the esri settings values. $.ajax({ type: "GET", dataType: "xml", url: endpointUrl }).success(function (data) { console.log("getesrisettings", data); var formattedData = DefaultEsriSettings; if ($(data).find('EsriSettings').length > 0) { $(data).find('EsriSettings').each(function () { $(this).children().each(function () { if ($(this).text() != "") { if (typeof(formattedData[this.tagName]) === 'number') formattedData[this.tagName] = parseFloat($(this).text()); else if (typeof formattedData[this.tagName] === 'boolean') formattedData[this.tagName] = ($(this).text() == 'true'); else formattedData[this.tagName] = $(this).text(); } }); }); console.log(formattedData); if (callback) { callback(formattedData); } } }).error(function (jqXHR, textStatus, errorThrown) { //if unsuccessful, generate an error alert message //console.log("Request failed: " + textStatus + "\n" + errorThrown); console.log('Esri Settings not found. loading map with no functionality.'); console.log("Please configure map settings for full functionality."); //showMessage("Please configure map settings for full functionality.", null, 100000, "alert-danger"); callback(DefaultEsriSettings); }); /* //Get the esri settings values. var PortalBuddyEsriUrl = Adoxio.Esri.RootApiUrl + "/settings/?entitylogicalname=" + typeName; $.ajax({ type: "GET", contentType: "application/json;", datatype: "json", url: PortalBuddyEsriUrl, }).success(function (data) { //console.log(data); var formattedData = DefaultEsriSettings; if (data.Attributes.length > 0) { var TempData = data.Attributes; $(TempData).each(function (index, item) { // console.log(item); formattedData[item.Key.replace(".", "_")] = item.Value.Value; }); console.log(formattedData); if (callback) { callback(formattedData); } } }).error(function (jqXHR, textStatus, errorThrown) { //if unsuccessful, generate an error alert message //console.log("Request failed: " + textStatus + "\n" + errorThrown); console.log('Esri Settings not found. loading map with no functionality.'); console.log("Please configure map settings for full functionality."); //showMessage("Please configure map settings for full functionality.", null, 100000, "alert-danger"); callback(DefaultEsriSettings); }); */ }; var DefaultEsriSettings = { // map settings map_abs_basemap: "topo", map_abs_initialzoom: 2, map_abs_latitude: 49.693684, map_abs_longitude: -96.844109, map_abs_pushpinimage: null, map_abs_pushpinwidth: 20, map_abs_pushpinheight: 20, map_abs_pushpinzoom: 16, map_abs_minzoom: 0, map_abs_maxzoom: 20, // map features map_abs_enablesearch: true, map_abs_showzoombuttons: true, map_abs_enablelocate: true, // requires https map_abs_showattribution: true, map_abs_enableclickreversegeocode: true, map_abs_allowintersectionaddress: true, map_abs_allowpointwithoutaddress: true, map_abs_allowrangeaddress: true, //spatial reference map_abs_spatialreference: 4326, //4326, // 102100, // map boundary map_abs_polygonboundary: null, map_abs_city: null, map_abs_stateorprovince: null, map_abs_neighborhood: null, map_abs_country: null, map_abs_postalcode: null, map_abs_enableBoundaryOnSearch: true, map_abs_allowunvalidatedaddress: false, map_abs_uselocationfieldforsearch: false, map_abs_geolocationonload: true, // field mappings mapping_abs_cityfieldname: "address1_composite_city", mapping_abs_countryfieldname: "address1_composite_country", mapping_abs_countyfieldname: "address1_composite_county", mapping_abs_latitudefieldname: "address1_composite_latitude", mapping_abs_line1fieldname: "address1_composite_line1", mapping_abs_line2fieldname: "address1_composite_line2", mapping_abs_line3fieldname: "address1_composite_line3", mapping_abs_locationfieldname: "address1_composite", mapping_abs_longitudefieldname: "address1_composite_longitude", mapping_abs_postalcodefieldname: "address1_composite_postalcode", mapping_abs_postofficeboxfieldname: "address1_composite_postofficebox", mapping_abs_stateorprovincefieldname: "address1_composite_stateorprovince", mapping_abs_neighborhoodfieldname: "address1_composite_neighborhood", // fields to attach onchange event for geocoding mapping_abs_geocodeactivationfieldnames: "address1_composite,subject", // server settings server_abs_geocoderesturl: "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?", server_abs_reversegeocoderesturl: "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?", server_abs_tokenurl: "https://www.arcgis.com/sharing/rest/oauth2/token/", server_abs_applicationtoken: null, server_abs_tokenexpiry: null, server_abs_esriserverid: null, server_abs_clientid: null, server_abs_clientsecret: null, server_abs_enabletoken: true }; var convertFieldstoComposite = function () { EsriSettings.mapping_abs_cityfieldname = EsriSettings.mapping_abs_cityfieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_countryfieldname = EsriSettings.mapping_abs_countryfieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_countyfieldname = EsriSettings.mapping_abs_countyfieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_latitudefieldname = EsriSettings.mapping_abs_latitudefieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_line1fieldname = EsriSettings.mapping_abs_line1fieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_line2fieldname = EsriSettings.mapping_abs_line2fieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_line3fieldname = EsriSettings.mapping_abs_line3fieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_longitudefieldname = EsriSettings.mapping_abs_longitudefieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_postalcodefieldname = EsriSettings.mapping_abs_postalcodefieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_postofficeboxfieldname = EsriSettings.mapping_abs_postofficeboxfieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_stateorprovincefieldname = EsriSettings.mapping_abs_stateorprovincefieldname.replace("_", "_composite_"); EsriSettings.mapping_abs_neighborhoodfieldname = EsriSettings.mapping_abs_neighborhoodfieldname.replace("_", "_composite_"); }; var typename = Adoxio.Esri.GetEntityName(); if (typename) { GetEsriSettings(typename, function (data) { EsriSettings = data; if (EsriSettings == null) { throw new Error("Esri Settings not set."); } if (EsriSettings.mapping_abs_locationfieldname.indexOf('composite') > -1) { convertFieldstoComposite(); //console.log('composite address', EsriSettings); } loadMap(sectionId, EsriSettings); }); } else { //console.log("loadmap"); loadMap(sectionId, DefaultEsriSettings); } } };