nm3clol-archived-russellcou.../russellcountyva.us/www.russellcountyva.us/Assets/Scripts/MapResult/MapResultEsri.js

869 lines
23 KiB
JavaScript

var MapResult = function ($) {
typeof define === "function" && define.amd && (define.amd = null);
$.ajaxSetup({ cache: false });
var mapResult = this;
var mapInitialized = false;
var map;
var locator;
var searchResultsArray;
var markersArray;
var markerImage;
var showControls;
var showInfoWindows;
var markerDragged;
var initialLoadingComplete;
var draggableMarkers;
var showFacilityId;
var suppliedZoom;
var basemapUrl;
var lat;
var lng;
var zoomInUse;
var WKID;
var currentMarker;
var basemap;
var markerImageUrl;
var infoWindowUrl;
var clusteredInfoWindowUrl;
var clusteredMarkerImageUrl;
var clusteredMarkerImage;
var infoWindowWidth = 350;
var infoWindowHeight = 175;
var clusteredInfoWindowWidth = 350;
var clusteredInfoWindowHeight = 200;
var mobileInfoWindowWidth = 165;
var mobileInfoWindowHeight = 150;
var clusteredMobileInfoWindowWidth = 165;
var clusteredMobileInfoWindowHeight = 150;
var meMarkerImage;
var meMarkerImageUrl = '/Assets/Images/MeMarker.png';
var cannotDetermineLocationError;
var locationAccuracyThreshold = 100000;
var meMarker = null;
$(document).ready(function () {
$('#infoWindowPrevious').keypress(function () {
$(this).click();
});
$(document).delegate('#infoWindowPrevious', 'click', function (e) {
e.preventDefault();
var curIndex = mapResult.getCurrentClusteredPositionIndex();
curIndex--;
mapResult.changeFacility(curIndex);
});
$('#infoWindowNext').keypress(function () {
$(this).click();
});
$(document).delegate('#infoWindowNext', 'click', function (e) {
e.preventDefault();
var curIndex = mapResult.getCurrentClusteredPositionIndex();
curIndex++;
mapResult.changeFacility(curIndex);
});
});
mapResult.initializeNulls = function () {
map = null;
locator = null;
searchResultsArray = null;
markersArray = null;
markerImage = null;
showControls = null;
showInfoWindows = null;
markerDragged = null;
initialLoadingComplete = null;
draggableMarkers = null;
showFacilityId = null;
suppliedZoom = null;
basemapUrl = null;
lat = null;
lng = null;
zoomInUse = null;
WKID = null;
currentMarker = null;
basemap = null;
markerImageUrl = null;
infoWindowUrl = null;
clusteredInfoWindowUrl = null;
clusteredMarkerImageUrl = null;
clusteredMarkerImage = null;
};
mapResult.initializeDefault = function () {
lat = $('#hdn_LatitudeForMap').val();
lng = $('#hdn_LongitudeForMap').val();
zoomInUse = parseInt($('#hdn_DefaultZoomForMap').val());
suppliedZoom = ($('hdn_ZoomForMap').val() == '') ? parseInt($('hdn_ZoomForMap').val()) : zoomInUse;
locator = new esri.tasks.Locator("https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
mapResult.initializeMap();
};
mapResult.initializeImages = function () {
mapResult.initializeMarkerImage();
};
mapResult.initializeMarkerImage = function () {
markerImage = new esri.symbol.PictureMarkerSymbol(
markerImageUrl,
25,
33
);
clusteredMarkerImage = new esri.symbol.PictureMarkerSymbol(
clusteredMarkerImageUrl,
25,
33
);
meMarkerImage = new esri.symbol.PictureMarkerSymbol(
meMarkerImageUrl,
25,
33
);
};
mapResult.setInfoWindowSize = function (clustered) {
if ($('#hdn_IsMobile').val() != undefined && $('#hdn_IsMobile').val() == 'True') {
if (clustered) {
map.infoWindow.resize(clusteredMobileInfoWindowWidth, clusteredMobileInfoWindowHeight);
} else {
map.infoWindow.resize(mobileInfoWindowWidth, mobileInfoWindowHeight);
}
} else {
if (clustered) {
map.infoWindow.resize(clusteredInfoWindowWidth, clusteredInfoWindowHeight);
} else {
map.infoWindow.resize(infoWindowWidth, infoWindowHeight);
}
}
};
mapResult.initializeStyles = function () {
$('#map_canvas').css('padding', 0);
$('#map_canvas').css('margin', 0);
$('#map_canvas').addClass('tundra');
};
mapResult.initializeVars = function () {
if ($('#hdn_BasemapUrl').val() != undefined) {
basemapUrl = $('#hdn_BasemapUrl').val();
} else {
basemapUrl = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer";
}
WKID = 102100;
dojo.require("esri.dijit.InfoWindow");
dojo.require("esri.virtualearth.VETiledLayer");
dojo.require("dijit.form.Button");
dojo.require("esri.tasks.locator");
if (window.FeatureToggles.isActive("CMS.JqueryUpgrade.UpgradeTo224") && $('#hdnModuleEligibleForJquery224Upgrade').val() == "true") {
if ($('#hdn_MapSearchResults').val() !== "")
searchResultsArray = $.parseJSON($('#hdn_MapSearchResults').val());
}
else {
searchResultsArray = $.parseJSON($('#hdn_MapSearchResults').val());
}
showControls = $('#hdn_ShowControls').val();
showInfoWindows = $('#hdn_ShowInfoWindows').val();
markerImageUrl = $('#hdn_MarkerImageUrl').val();
infoWindowUrl = $('#hdn_InfoWindowUrl').val();
clusteredInfoWindowUrl = $('#hdn_ClusteredInfoWindowUrl').val();
clusteredMarkerImageUrl = $('#hdn_ClusteredMarkerImageUrl').val();
cannotDetermineLocationError = $('#hdn_CannotDetermineLocationError').val();
if ($('#hdn_DraggableMarkers').val() != null && $('#hdn_DraggableMarkers').val() == 'True') {
draggableMarkers = true;
}
else {
draggableMarkers = false;
}
if ($('#hdn_ShowID').val() != null) {
showFacilityId = parseInt($('#hdn_ShowID').val());
}
else {
showFacilityId = 0;
}
markersArray = new Array();
initialLoadingComplete = false;
markerDragged = false;
};
mapResult.initializeEsriMap = function () {
dojo.require("esri.map");
dojo.addOnLoad(mapResult.initializeDefault);
};
mapResult.initialize = function () {
//Check already mapinitialized and user is not searching the facility
if (mapInitialized && !$('#mapResultTab').length) {
return;
}
mapResult.initializeNulls();
mapResult.initializeVars();
mapResult.initializeStyles();
mapResult.initializeEsriMap();
mapInitialized = true;
};
mapResult.setInfoWindowEvent = function () {
dojo.connect(map.graphics, 'onClick', mapResult.showInfoWindowByEvent);
};
mapResult.postDefaultMapInitialization = function () {
dojo.connect(window, "resize", map, map.resize);
map.enableMapNavigation();
mapResult.setCenterAndZoom();
mapResult.initializeImages();
mapResult.fillMarkersArray();
if (showFacilityId == 0) {
if (searchResultsArray != null && searchResultsArray.length > 0) {
mapResult.findClosestMarker();
} else {
setTimeout(function () { mapResult.tryToGeocode(); }, 500);
}
}
mapResult.putMarkers();
if (window.location.href.toLowerCase().indexOf('/admin/') == -1) {
mapResult.checkSharedLocation();
}
mapResult.setInfoWindowSize(false);
if (showControls == 'True') {
map.showZoomSlider();
}
else {
map.hideZoomSlider();
map.hidePanArrows();
}
if (showInfoWindows != null && showInfoWindows == 'True') {
mapResult.setInfoWindowEvent();
}
else {
if ($('#hdn_DraggableMarkers').val() != null && $('#hdn_DraggableMarkers').val() == 'True') {
dojo.connect(map, 'onClick', mapResult.handleMapClick);
}
}
if (showFacilityId > 0) {
if (showInfoWindows != null && showInfoWindows == 'True') {
mapResult.showInfoWindowByID(showFacilityId);
}
else if (!initialLoadingComplete) {
mapResult.findClosestMarker();
initialLoadingComplete = true;
}
setTimeout(mapResult.reloadAndCenter, 1000);
}
};
mapResult.handleMapClick = function (event) {
if (markersArray != null && markersArray.length > 0 && markersArray[0] != null) {
markerDragged = true;
markersArray[0].setGeometry(event.mapPoint);
markersArray[0].attributes.accuracy = 'USER_DEFINED';
}
else {
markerDragged = true;
mapResult.markAddress(event.location, true, 'USER_DEFINED');
}
};
mapResult.reloadAndCenter = function () {
if (!initialLoadingComplete) {
mapResult.resizeMap();
initialLoadingComplete = true;
}
};
mapResult.addQueryStringToDetailsLinkUrl = function (link) {
var addToUrl = '&centerLat=' + mapResult.getMapPoint(map.extent.getCenter()).y
+ '&centerLng=' + mapResult.getMapPoint(map.extent.getCenter()).x
+ '&zoom=' + map.getLevel();
$(link).attr('href', link.href + '?' + addToUrl);
return true;
};
mapResult.tryToGeocode = function () {
mapResult.geoCodeAndCenter(
$('#hdn_AddressForGeocoding').val(),
parseInt($('#hdn_ZoomForMap').val()),
null,
false,
false);
};
mapResult.geoCodeAndCenter = function (address, zoom, errorMessage, markAddress, isDraggable) {
if (address != null && address != '' && zoom != null && zoom != '') {
var singleAddress = {
'SingleLine': address
};
var options = {
address: singleAddress,
outFields: ["*"]
};
locator.addressToLocations(
options,
function (results) {
if (results.length > 0) {
mapResult.geoCodeAndCenterSuccessFunction(results, zoom, markAddress, isDraggable, errorMessage);
}
else {
mapResult.promptError(errorMessage);
}
},
function () {
mapResult.promptError(errorMessage);
}
);
}
else {
mapResult.promptError(errorMessage);
}
};
mapResult.filteringGeocodeSuccessFunction = function (resultsZipcode, address, zoom, errorMessage, markAddress, isDraggable) {
var singleAddress = {
'SingleLine': address
};
var options = {
address: singleAddress,
outFields: ["*"]
};
locator.addressToLocations(
options,
function (results) {
if (results.length > 0) {
mapResult.geoCodeAndCenterSuccessFunction(results, zoom, markAddress, isDraggable, errorMessage);
}
else {
mapResult.promptError(errorMessage);
}
},
function () {
mapResult.promptError(errorMessage);
}
);
};
mapResult.geoCodeAndCenterWithZipcode = function (address, zoom, errorMessage, markAddress, isDraggable, zipcode) {
if (address != null && address != '' && zoom != null && zoom != '' && zipcode != null) {
var singleAddress = {
'SingleLine': address
};
var options = {
address: singleAddress,
outFields: ["*"]
};
locator.addressToLocations(
options,
function (results) {
if (results.length > 0) {
if (results[0].score > 70)
mapResult.geoCodeAndCenterSuccessFunction(results, zoom, markAddress, isDraggable, errorMessage);
else
mapResult.promptError(errorMessage);
} else {
mapResult.promptError(errorMessage);
}
},
function () {
mapResult.promptError(errorMessage);
}
);
}
else {
mapResult.promptError(errorMessage);
}
};
mapResult.geoCodeAndCenterSuccessFunction = function (results, zoom, markAddress, isDraggable, errorMessage) {
if (markAddress && !mapResult.isAcceptableAccuracy(results[0].score)) {
mapResult.promptError(errorMessage);
}
lat = results[0].location.y;
lng = results[0].location.x;
zoomInUse = zoom;
mapResult.setCenterAndZoom();
if (markAddress) {
mapResult.markAddress(mapResult.makeALocation(results[0].location.y, results[0].location.x), isDraggable, results[0].score);
}
};
mapResult.promptError = function (errorMessage) {
if (errorMessage != null && errorMessage != '') {
alert(errorMessage);
}
};
mapResult.geoCodeAndMakeLatLngQueryString = function (address, successCallback, errorCallback) {
var timedOut = false;
var timerId;
if (address != null) {
var singleAddress = {
'SingleLine': address
};
var options = {
address: singleAddress,
outFields: ["*"]
};
locator.addressToLocations(
options,
function (results) {
if (timedOut) {
return;
}
else {
clearTimeout(timerId);
}
if (results.length > 0) {
successCallback(
results[0].location.y,
results[0].location.x,
results[0].score
);
}
else {
clearTimeout(timerId);
errorCallback(false);
}
},
function () {
clearTimeout(timerId);
errorCallback(false);
}
);
timerId = setTimeout(function () {
timedOut = true;
errorCallback(true);
}, 5000);
}
};
mapResult.isAcceptableAccuracy = function (accuracy) {
if ((markerDragged) || (parseFloat(accuracy) > 25.0)) {
return true;
}
else {
return false;
}
};
mapResult.clearOverlays = function () {
map.graphics.clear();
};
mapResult.getFirstMarkerLatitude = function () {
if (markersArray != null && markersArray[0] != null) {
return mapResult.getMapPoint(markersArray[0].geometry).y;
}
return null;
};
mapResult.getFirstMarkerLongitude = function () {
if (markersArray != null && markersArray[0] != null) {
return mapResult.getMapPoint(markersArray[0].geometry).x;
}
return null;
};
mapResult.getFirstMarkerAccuracy = function () {
if (markersArray != null && markersArray[0] != null) {
if (markerDragged) {
return 'USER_DEFINED';
} else {
return markersArray[0].attributes.accuracy;
}
}
return null;
};
mapResult.markAddress = function (location, isDraggable, accuracy) {
if (location != null) {
mapResult.clearOverlays();
markersArray = new Array();
markersArray[0] = makeANewMarker(location, 0, accuracy);
mapResult.putMarkers();
}
};
mapResult.makeANewMarker = function (location, id, accuracy, title) {
var result;
if (id.toString().indexOf('-') === -1) {
result = new esri.Graphic(location, markerImage);
} else {
result = new esri.Graphic(location, clusteredMarkerImage);
}
result.setAttributes({
"id": id,
"accuracy": accuracy,
"Title": title
});
return result;
};
mapResult.geoCodeAndMarkAnAddress = function (address, zoom, errorMessage, isDraggable) {
mapResult.geoCodeAndCenter(address, zoom, errorMessage, true, isDraggable);
};
mapResult.geoCodeAndMarkAnAddressWithZipcode = function (address, zoom, errorMessage, isDraggable, zipcode) {
mapResult.geoCodeAndCenterWithZipcode(address, zoom, errorMessage, true, isDraggable, zipcode);
};
mapResult.fillMarkersArray = function () {
if (searchResultsArray != null) {
for (var i = 0; i < searchResultsArray.length; i++) {
if (searchResultsArray[i].AccuracyV3 != 'APPROXIMATE') {
markersArray[i] = mapResult.makeANewMarker(
mapResult.makeALocation(
parseFloat(searchResultsArray[i].Latitude)
, parseFloat(searchResultsArray[i].Longitude))
, searchResultsArray[i].ID
, searchResultsArray[i].Accuracy
, searchResultsArray[i].Name
);
}
}
}
};
mapResult.checkSharedLocation = function () {
if (navigator != null && navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
mapResult.sharedLocationSuccess,
mapResult.sharedLocationError
);
}
};
mapResult.sharedLocationError = function (error) {
if (error.code != 1) {
alert(cannotDetermineLocationError + ' ' + error.message + '.');
}
};
mapResult.sharedLocationSuccess = function (location) {
if (location.coords.accuracy > locationAccuracyThreshold) {
alert(cannotDetermineLocationError);
} else {
mapResult.addSharedLocation(location);
}
};
mapResult.addSharedLocation = function (location) {
meMarker = new esri.Graphic(mapResult.makeALocation(location.coords.latitude, location.coords.longitude), meMarkerImage);
meMarker.setAttributes({
"id": 0,
"accuracy": 0,
"Title": 'Me'
});
map.graphics.add(meMarker);
};
mapResult.putMarkers = function () {
if (markersArray != null) {
for (var i = 0; i < markersArray.length; i++) {
if (markersArray[i] != null) {
map.graphics.add(markersArray[i]);
}
}
}
};
mapResult.showInfoWindow = function (id, mapPoint, screenPoint, title) {
var url;
if (id.toString().indexOf('-') === -1) {
url = infoWindowUrl;
mapResult.setInfoWindowSize(false);
} else {
url = clusteredInfoWindowUrl;
mapResult.setInfoWindowSize(true);
}
$.ajax({
url: url,
type: 'GET',
data: { id: id },
datatype: 'html',
success: function (response) {
map.infoWindow.setContent(response);
return false;
},
error: function (xhr) {
alert("Error: " + xhr.statusText + "\nStatus: " + xhr.status);
if ($('#log').length > 0)
$('#log').html(xhr.responseText);
},
complete: function () {
}
});
map.infoWindow.setTitle(title);
//map.infoWindow.show(mapPoint, map.getInfoWindowAnchor(screenPoint));
mapResult.showInfoWindowAutoPan(screenPoint);
};
mapResult.showInfoWindowAutoPan = function (screenPoint) {
map.infoWindow.show(screenPoint);
map.infoWindow.reposition();
};
mapResult.showInfoWindowByEvent = function (event) {
if (event.graphic.attributes.id != 0) {
mapResult.showInfoWindow(event.graphic.attributes.id, event.screenPoint, event.screenPoint, event.graphic.attributes.Title);
}
};
mapResult.hideHoveringTitle = function (event) {
map.graphics.remove(currentMarker);
currentMarker = undefined;
};
mapResult.showHoveringTitle = function (event) {
if (currentMarker == undefined) {
var textSymbol = new esri.symbol.TextSymbol(event.graphic.attributes.Title);
textSymbol.setAlign('ALIGN_END');
currentMarker = new esri.Graphic(event.mapPoint, textSymbol);
map.graphics.add(currentMarker);
}
};
mapResult.showInfoWindowByID = function (id) {
var marker;
var i;
if (!initialLoadingComplete) {
if (markersArray != null && markersArray.length > 0) {
for (i = 0; i < markersArray.length; i++) {
if (markersArray[i] != null) {
if (markersArray[i].attributes.id != undefined && markersArray[i].attributes.id == id) {
marker = markersArray[i];
}
}
}
}
if (marker != null) {
mapResult.showInfoWindow(marker.attributes.id, marker.geometry, marker.geometry, marker.attributes.Title);
map.centerAt(marker.geometry);
initialLoadingComplete = true;
}
}
};
mapResult.resizeMap = function () {
var ex = null;
if (map.graphics.graphics.length > 1) {
ex = esri.graphicsExtent(map.graphics.graphics);
} else if (map.graphics.graphics.length > 0) {
var geo = map.graphics.graphics[0].geometry;
map.centerAndZoom(geo, 19);
} else {
ex = map.extent;
}
if (ex) {
var diffX = ex.xmax - ex.xmin;
var diffY = ex.ymax - ex.ymin;
var length = Math.max(diffX, diffY);
if (length < 150) {
var center = ex.getCenter();
map.centerAndZoom(center, 19);
} else {
map.setExtent(ex, true);
};
}
};
mapResult.makeAnExtent = function (geometry) {
return new esri.geometry.Extent(
geometry.x,
geometry.y,
geometry.x,
geometry.y,
new esri.SpatialReference({ wkid: MapResult.WKID })
)
};
mapResult.findClosestMarker = function () {
var lat1 = mapResult.getMapPoint(map.extent.getCenter()).y;
var lon1 = mapResult.getMapPoint(map.extent.getCenter()).x;
var pi = Math.PI;
var R = 6371;
var distances = [];
var closest = -1;
for (i = 0; i < markersArray.length; i++) {
if (markersArray[i] != null) {
var lat2 = markersArray[i].geometry.y;
var lon2 = markersArray[i].geometry.x;
var chLat = lat2 - lat1;
var chLon = lon2 - lon1;
var dLat = chLat * (pi / 180);
var dLon = chLon * (pi / 180);
var rLat1 = lat1 * (pi / 180);
var rLat2 = lat2 * (pi / 180);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(rLat1) * Math.cos(rLat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
distances[i] = d;
if (closest == -1 || d < distances[closest]) {
closest = i;
}
}
}
if (closest != -1 && closest != i) {
map.centerAt(markersArray[closest].geometry);
}
};
mapResult.initializeMap = function () {
if (dijit.registry.byId("map_canvas_infowindow") != undefined) {
dijit.registry.byId("map_canvas_infowindow").destroyRecursive();
}
if (dijit.registry.byId("map_canvas_zoom_slider") != undefined) {
dijit.registry.byId("map_canvas_zoom_slider").destroyRecursive();
}
var initExtent = new esri.geometry.Extent({ "xmin": -130, "ymin": 5, "xmax": -70, "ymax": 65, "spatialReference": { "wkid": WKID } });
map = new esri.Map("map_canvas", { wrapAround180: true, nav: true, extent: initExtent });
basemap = new esri.layers.ArcGISTiledMapServiceLayer(basemapUrl);
map.addLayer(basemap);
if (map.loaded) {
init()();
}
else {
dojo.connect(map, "onLoad", mapResult.postDefaultMapInitialization);
}
};
mapResult.setCenterAndZoom = function () {
map.centerAndZoom(makeALocation(lat, lng), zoomInUse);
};
mapResult.makeALocation = function (pointLat, pointLng) {
var point = new esri.geometry.Point(pointLng, pointLat, new esri.SpatialReference({ wkid: WKID }));
var mapPoint = esri.geometry.geographicToWebMercator(point);
return mapPoint;
};
mapResult.getMapPoint = function (point) {
return esri.geometry.webMercatorToGeographic(point);
};
mapResult.triggerResize = function () {
mapResult.resizeMap();
};
mapResult.getMap = function () {
return map;
};
mapResult.getMarkersArray = function () {
return markersArray;
};
mapResult.getClusteredIDArray = function () {
var result = [];
var ids = $('#hdn_clusteredIdList').val().split(',');
for (var i = 0; i < ids.length; i++) {
result[i] = parseInt(ids[i]);
}
return result;
};
mapResult.getCurrentClusteredID = function () {
return parseInt($('#hdn_clusteredCurrentFacilityID').val());
};
mapResult.getCurrentClusteredPositionIndex = function () {
return parseInt($('#hdn_clusteredIdListCurPos').val());
};
mapResult.setCurrentClusteredPositionIndex = function (curIndex) {
$('#hdn_clusteredIdListCurPos').val(curIndex);
};
mapResult.getCurrentClusterPosition = function (ids, id) {
for (var i = 0; i < ids.length; i++) {
if (ids[i] == id) {
return i;
}
}
};
mapResult.handleClusteredTitle = function (current, total) {
$('.title').html((current + 1) + ' of ' + total);
};
mapResult.changeFacility = function (curIndex) {
if (curIndex != undefined) {
var idList = mapResult.getClusteredIDArray();
if (curIndex > (idList.length - 1)) {
curIndex = 0;
} else if (curIndex < 0) {
curIndex = idList.length - 1;
}
mapResult.setCurrentClusteredPositionIndex(curIndex);
var id = idList[curIndex];
mapResult.ajaxCall(infoWindowUrl, 'GET', { id: id, isClustered: true }, 'html', mapResult.processClusteredFacilityResponse);
mapResult.handleClusteredTitle(curIndex, idList.length);
}
};
mapResult.ajaxCall = function (url, type, data, dataType, processResponseFunction) {
$.ajax({
url: url,
type: type,
data: data,
datatype: dataType,
success: function (response) {
processResponseFunction(response);
return false;
},
error: function (xhr) {
alert("Error: " + xhr.statusText + "\nStatus: " + xhr.status);
if ($('#log').length > 0)
$('#log').html(xhr.responseText);
},
complete: function () {
}
});
};
mapResult.processClusteredFacilityResponse = function (response) {
$('.clusteredInfoWindowContent').replaceWith(response);
};
return this;
}(jQuery);