ArcGIS Javascript API - Polygon not showing up - javascript

Please find polygon code as below. It works only with hard-coded data and not with data passed through database.
I want to change this so data is passed through database, not hardcoded.
Polygon comes from database in following format:
var data = "POLYGON ((174.605111568859 -37.119413675388707, 174.6051123299834 -37.119449718193458, 174.60515905129122 -37.119530204987136, 174.60540067619004 -37.119779304335452, 174.60554255499551 -37.120101860545844, 174.60568043759687 -37.120235191897571, 174.60572696965184 -37.1203066677341, 174.60572849253467 -37.120378753310746, 174.60570674933629 -37.120415100973361, 174.60560757225889 -37.120515590528086, 174.60554177129595 -37.120597601350227, 174.60549026791193 -37.120823630882519, 174.6054873903158 -37.121220253972716, 174.605111568859 -37.119413675388707))"
I'm calling following function to load ESRI maps:
function LoadEsriTrees() {
var $mover = $('#thingtypecontent');
$mover.find('div#mapDiv').empty();
//it gives polygon data as prescribed in above format
var polygonData = $mover.find('input#hdndata').val();
//following code formats polygon data in required format
var check1 = (polygonData.indexOf("POLYGON ((") !== -1);
if (check1 == true)
polygonData = polygonData.replace('POLYGON ((', '[[');
var check2 = (polygonData.indexOf("))") !== -1);
if (check2 == true)
polygonData = polygonData.replace('))', ']]');
polygonData = polygonData.replace(/,\s+/g, '],[');
//create polygon data
var coords = new Array();
var allLocs = new Array();
var anchorLat = null;
var anchorLon = null;
coords = polygonData.split(" ");
var thisLocs = new Array();
var anchorCoord = null;
if ((coords.length / 2) % 2) {
anchorCoord = coords.length / 2 - 1;
}
else {
anchorCoord = coords.length / 2;
}
for (k = 0; k <= coords.length - 1; k = k + 2) {
var thisLoc = [coords[k], coords[k + 1]];
thisLocs.push(thisLoc);
allLocs.push(thisLoc);
if (k == anchorCoord) {
anchorLat = coords[k + 1];
anchorLon = coords[k];
}
}
//thisLocs finally presents data in following format:
thisLocs = [[174.605111568859, -37.119413675388707],[ 174.6051123299834, -37.119449718193458],[ 174.60515905129122, -37.119530204987136],[ 174.60540067619004, -37.119779304335452],[ 174.60554255499551, -37.120101860545844],[ 174.60568043759687 , -37.120235191897571],[ 174.60572696965184 , -37.1203066677341],[ 174.60572849253467, -37.120378753310746],[ 174.60570674933629 , -37.120415100973361],[ 174.60560757225889, -37.120515590528086],[ 174.60554177129595, -37.120597601350227],[ 174.60549026791193, -37.120823630882519],[ 174.6054873903158, -37.121220253972716],[ 174.605111568859, -37.119413675388707]]
var map;
require([
"esri/map",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/SimpleLineSymbol",
"dojo/_base/Color",
"esri/graphic",
"esri/geometry/Polygon",
"dojo/on",
"dojo/dom",
"dojo/domReady!"
],
function (
Map, SimpleFillSymbol, SimpleLineSymbol, Color,
Graphic, Polygon,
on, dom
) {
map = new Map("mapDiv", {
center: [174.605369, -37.120276],
zoom: 15,
basemap: "streets"
});
on(map, "load", addGraphic);
var sfs = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25])
)
function addGraphic() {
// Draw polygon
var singleRingPolygon = new esri.geometry.Polygon(); singleRingPolygon.addRing(thisLocs);
singleRingPolygon.spatialReference = new esri.SpatialReference({ wkid: 4326 });
var poly_wm = esri.geometry.geographicToWebMercator(singleRingPolygon);
var gra = new Graphic(poly_wm, sfs);
map.graphics.add(gra);
}
});
}
If value of thisLocs is hard-coded in singleRingPolygon.addRing(thisLocs) it works fine, but not the above way.

Not sure why and if you're still having problems, but maybe it will help someone else. I had to use eval(thisLocs) for it to work for me.

Related

check if a lat long is within an extent using open layers 3

I have a UK county shape file (Multipolygon) using EPSG:4326 in my geoserver. I'm using open layers 3 to load this shape file in my application as below :
source = new ol.source.XYZ({url: '/gmaps?zoom={z}&x={x}&y={y}&Layers=UKCounties', crossOrigin: "anonymous"});
countiesLayer = new ol.layer.Tile({source: source});
map.addLayer(countiesLayer);
This works well. I have a requirement to get users current location which is done as
var coordinate = geolocation.getPosition();
I'm able to retrieve the correct lat & long here. Ex : Lat = 53.797534899999995, Lng = -1.5449. now I need to check which of the counties (polygon) these points are in using open layers 3 & Javascript.
Using Geoserver WFS, I'm able to get the bounding box of each of the counties as
$.each(features, function(index, eachFeature) {
var bbox = eachFeature.properties.bbox;
if (bbox != null) {
var bottomLeft = ([bbox[0], bbox[1]]);
var topRight = ([bbox[2], bbox[3]]);
var extent = new ol.extent.boundingExtent([bottomLeft, topRight]);
if (ol.extent.containsXY(extent1,lat,long)) {
alert("got the feature");
}
}
});
The issue is my code doesn't print the alert statement.I've also tried using
if (ol.extent.containsXY(extent,long,lat))
and
var XY = ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');
if (ol.extent.containsXY(extent,XY[0],XY[1]))
if (ol.extent.containsXY(extent,XY[1],XY[0]))
But none of these print the alert. Is there anything wrong in this?
Before answering your question, I did not know the method of "ol.extent.containsXY".
I used my poor logic! I detected a feature if in a polygon by follwing :
transform feature and container(polygon) to coordinate [lon, lat]
detect the container if contain the feature
extent array rule [minLon, minLat, maxLon, maxLat]
code snippet: (my destinationPro:'EPSG:3857', sourcePro:'EPSG:4326')
QyGIS.prototype.isInner = function(featureExtent, containerExtent) {
var featureLonLat = ol.proj.transformExtent(featureExtent, destinationPro, sourcePro);
var containerLonLat = ol.proj.transformExtent(containerExtent, destinationPro, sourcePro);
// in my condition, the feature is a point, so featureLonLat[0] = featureLonLat[2], featureLonLat[1] = featureLonLat[3]. what's more extent have four value in a array so the loop length is 4
for (var i = 0; i < featureLonLat.length; i++) {
/* actually:
featureLonLat[0] < containerLonLat[0] || featureLonLat[0] > containerLonLat[2]
featureLonLat[1] < containerLonLat[1] || featureLonLat[1] > containerLonLat[3]
featureLonLat[2] < containerLonLat[0] || featureLonLat[2] > containerLonLat[2]
featureLonLat[3] < containerLonLat[1] || featureLonLat[3] > containerLonLat[3]
*/
if (featureLonLat[i] < containerLonLat[i % 2] || featureLonLat[i] > containerLonLat[i % 2 + 2]) {
return false;
}
}
return true;
};
QyGIS.prototype.getInnerFeatures = function(layerName, extent) {
var self = this;
var layer = self.getLayer(layerName);
if (layer) {
var source = layer.getSource();
var features = source.getFeatures();
for (var i = 0; i < features.length; i++) {
var curFeatureExtent = features[i].getGeometry().getExtent();
if (self.isInner(curFeatureExtent, extent)) {
console.log(features[i].get('name') + 'in area');
}
}
}
};
At last, sorry for my poor english if my answer confuse you .
I had to use
var XY = ol.extent.applyTransform(extent, ol.proj.getTransform("EPSG:3857", "EPSG:4326"));
instead of
var XY = ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');
and it works.

Passing Two dimension array from vb.net to javascript

<script>
var map,imageServiceLayer;
var clr_default = [[164355, 71, 107, 161]];
var clr_custom;
require([
"esri/map", "esri/layers/ArcGISImageServiceLayer",
"esri/layers/ImageServiceParameters", "dojo/parser", "dojo/domReady!"
], function(
Map, ArcGISImageServiceLayer,
ImageServiceParameters, parser
) {
parser.parse();
esri.config.defaults.io.corsEnabledServers.push("http://mapsdev.lib.purdue.edu:6080");
map = new Map("map", {
basemap: "topo",
center: [-100, 33],
zoom: 5
});
var rasterFunction = new esri.layers.RasterFunction();
var arguments = {};
arguments.Colormap=clr_default;
rasterFunction.arguments = arguments;
rasterFunction.functionName = "Colormap";
var params = new ImageServiceParameters();
//params.renderingRule=rasterFunction;
imageServiceLayer = new ArcGISImageServiceLayer("http://mapsdev.lib.purdue.edu:6080/arcgis/rest/services/ISEE/ISEE2Dev_IN_DBO_gSSURGO_IN_10m/ImageServer", {
imageServiceParameters: params,
opacity: 0.75
});
map.addLayer(imageServiceLayer);
});
function changeColor(val){
var rasterFunction = new esri.layers.RasterFunction();
var arguments = {};
if (val == "Default")
imageServiceLayer.setRenderingRule(null);
else if (val == "Default1")
{
arguments.Colormap=clr_default;
rasterFunction.arguments = arguments;
rasterFunction.functionName = "Colormap";
imageServiceLayer.setRenderingRule(rasterFunction);
}
else if (val == "Custom")
{
arguments.Colormap=clr_custom;
rasterFunction.arguments = arguments;
rasterFunction.functionName = "Colormap";
imageServiceLayer.setRenderingRule(rasterFunction);
}
}
</script>
Dim sb As New StringBuilder
sb.Append("var clr_custom=new Array(" & (i + 1) & ");")
For j As Integer = 0 To i
sb.Append("clr_custom[" & j & "]=new Array(4);")
For k As Integer = 0 To 3
sb.Append("clr_custom[" & j & "][" & k & "]=" & color(j, k) & ";")
Next
Next
This is my java script.In fourth line the variable clr_custom is two dimension array and need to get values from server database and i tried doing that as shown above in vb.net.One way is to use registerstartupscript() for whole javascript,but this makes difficult to edit java script.Is there any simple to define the variable value in vb.net and use the same variable in javascript
It would seem you just want <%= sb.ToString() %> in the middle of your javascript.

TypeError: g is not a function

While re-writing one of my applications from scratch (to go from legacy to AMD) I'm encountering an error which I can't figure out. It is driving me crazy. I'm probably just misspelling something or have another minor mistake, but I just can't figure out what. Any help would be highly appreciated!
I'm still in development mode, so my code isn't that pretty at this time. You can see it live in action at here: http://tpgrf.nl/testserver/alpha/topotrainer/flevoland
The javascript code:
//Define area and url's
var currentPath = window.location.pathname.split('/');
var AREA = currentPath[currentPath.length - 2];
if (AREA == 'europa' || AREA == 'wereld' || AREA == 'nederland') {
var AREAURL = AREA;
var AREAisProvince = false;
} else {
AREAURL = 'nederland';
var AREAisProvince = true;
}; //Ondervang provincies
var basemapURL = window.location.protocol + "//tiles.arcgis.com/tiles/nSZVuSZjHpEZZbRo/arcgis/rest/services/Topografie_in_de_klas_" + AREAURL + "_ondergrond/MapServer";
var contentFeatureURL = window.location.protocol + "//services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_" + AREAURL + "/FeatureServer/0";
var CONTENT = 'cito100'; //Default to 'cito100', user can adjust manually
var TYPES = ''; //empty for now, will be defined later by the user
var TYPES = 'plaats'; //for testingunction's//
//
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
});
return uuid;
};
//
//Figure something out here to detect if the user as a new or returning visitor
//
//////////////////////////////////////
//Create a basemap and load features//
//////////////////////////////////////
var dojoConfig = { parseOnLoad: true };
var map;
require(["esri/geometry/Extent", "esri/SpatialReference", "esri/map", "esri/graphic", "esri/layers/ArcGISTiledMapServiceLayer", "esri/tasks/query", "esri/tasks/QueryTask", "esri/tasks/FeatureSet", "esri/layers/GraphicsLayer", "esri/Color", "esri/symbols/SimpleMarkerSymbol", "esri/symbols/SimpleLineSymbol", "esri/symbols/PictureMarkerSymbol", "esri/renderers/UniqueValueRenderer", "esri/renderers/ClassBreaksRenderer",
"dijit/layout/BorderContainer", "dijit/layout/ContentPane", "dijit/TitlePane",
"dojo/domReady!", "dojo/dom", "dojo/on"],
function (Extent, SpatialReference, Map, Graphic, Tiled, Query, QueryTask, FeatureSet, GraphicsLayer, Color, SimpleMarkerSymbol, SimpleLineSymbol, PictureMarkerSymbol, UniqueValueRenderer, ClassBreaksRenderer, dom, on) {
//#TODO: Can we actually define this on the basemap mapserver?
if (AREA == 'nederland' || AREAisProvince == true) {
var initExtent = new Extent(-165715, 6453119, 1435181, 7205260, new SpatialReference({ wkid: 102100 }));
}
if (AREA == 'europa') {
var initExtent = new Extent(-2827847, 2851709, 6838658, 11375669, new SpatialReference({ wkid: 102100 }));
}
if (AREA == 'wereld') {
var initExtent = new Extent(-19705424, -14849545, 21700207, 21624981, new SpatialReference({ wkid: 102100 }));
}
map = new Map("map", {
extent: initExtent
});
//let's add a basemap
var tiled = new Tiled(basemapURL);
map.addLayer(tiled);
where = 'Cito100_onderdeel=1';
if (AREAisProvince == true) {
where += ' AND Provincie=\'' + AREA + '\'';
}
map.on("load", getFeaturesToMapAndStorage(where));
function getFeaturesToMapAndStorage(whereClause) {
console.log(whereClause);
//query the featureService
var query = new Query();
query.returnGeometry = true;
query.outFields = ["*"];
query.outSpatialReference = new SpatialReference({ wkid: 102100 });
query.where = whereClause;
var queryTask = new QueryTask(contentFeatureURL);
queryTask.on("complete", function (event) {
//map.graphics.clear();
var featureGraphicsLayer = new GraphicsLayer();
//#TODO: Can't we find a way to use the symbols from the featurservice directly, instead of the url's?
defaultSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 10,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
new Color([255, 0, 0]), 1),
new Color([0, 255, 0, 0.25]));
var renderer = new UniqueValueRenderer(defaultSymbol, "Type");
renderer.addValue("Plaats", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/89e5f81878a69f9cc0525c841f98af54", 11, 11));
renderer.addValue("Gebied", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/165c76bd4465728a34f6d18df4a1ec03", 28, 28));
renderer.addValue("Water", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/f9c146a401f48c4f38202e83c2e4582a", 22, 22));
renderer.addValue("Provincie", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/7a5373d8f1dcd1ecc03cefbab687b97c", 38, 32));
renderer.addValue("Land", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_europa/FeatureServer/0/images/7a5373d8f1dcd1ecc03cefbab687b97c", 38, 32));
renderer.addValue("Werelddeel", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_wereld/FeatureServer/0/images/48f2256a49253388488d813d721c054b", 32, 38));
var features = event.featureSet.features;
var featureCount = features.length;
for (var i = 0; i < featureCount; i++) {
var graphic = features[i];
featureGraphicsLayer.add(graphic);
}
featureGraphicsLayer.renderer = renderer;
map.addLayer(featureGraphicsLayer);
//#TODO: Update localstorage
}); //end on queryTask complete
queryTask.execute(query, queryComplete);
function queryComplete() {
console.log("fire function queryComplete");
//#TODO: reset progressbar
}; //End function queryComplete
} //end function getFeaturesToMapAndStorage
//The two closing tags below are essential and close the complete DOJO part.
} //end function after require (AMD style)
); //end require
Your issue is with: map.on("load", getFeaturesToMapAndStorage(where));
You're calling getFeaturesToMapAndStorage which returns undefined, and passing that in as the "load" handler. I'm guessing that the minified version of whatever it is that you're using uses g as a reference to your handler.
Since g is undefined, you're basically saying undefined(loadEvent).
EDIT: I'm guessing you meant to do something like this:
map.on("load", function(){
getFeaturesToMapAndStorage(where);
});
EDIT 2: For clarity, I'll explain what was wrong in more detail.
The difference between what you had and what I suggested above, is that you were calling getFeaturesToMapAndStorage on the line containing map.on("load", getFeaturesToMapAndStorage(where)); (as opposed to calling it after map's load event). In order to call your function getFeaturesToMapAndStorage with a predetermined parameter, you need to call it from a function (like the anonymous function above - function(){...}) that would then be passed in as the event handler.
Alternatively, due to how you have things scoped, you could reference your where inside of getFeaturesToMapAndStorage in place of having a whereClause parameter.

dragging problem in markers in google maps

I am taking marker details from a database.
The code is
app.entries[id].data = {'id': id, 'map': entry[1].innerHTML,'type_id':
entry[2].innerHTML,'name': entry[3].innerHTML,'descript': entry[4].innerHTML, 'parish':
entry[5].innerHTML,'zip': entry[6].innerHTML, 'url': entry[7].innerHTML, 'lng':
entry[8].innerHTML,'lat':entry[9].innerHTML,'tags':entry[10].innerHTML,'img':
entry[11].innerHTML,'imgs':entry[12].innerHTML};
app.entries[id].data.imgHTML = (app.entries[id].data.img == "") ? "" :
fill_template(app.entries[id].data,app.infoWindowImageHTML);
var str = fill_template(app.entries[id].data,app.searchRowHTML);
html.push(str);
if (app.entries[id].data.lat != 0 || app.entries[id].data.lng != 0) {
var point = new GLatLng(app.entries[id].data.lat,app.entries[id].data.lng);
var m = new GMarker(point,{draggable: true});
GEvent.addListener(m, "dragstart", function() {
// map.closeInfoWindow();
var latlngold = m.getLatLng();
});
GEvent.addListener(m, "dragend", function() {
var m = new GMarker(point,{draggable: true});
m.entry_id = id;
var p=m.entry_id;
var latlngnew = m.getLatLng();
alert(latlngnew);
//m.setLatLng(new GLatLng(latlng));
editentry1(latlngnew,p);
});
}
The dragend and dragstart function always takes the last marker's details not the details of dragging marker..
function editentry1(latlngnew,p){
var newlat=latlngnew.lat();
var newlng=latlngnew.lng();
var d = new Date();
var dv = d.valueOf();
var url = "<?php echo $g['appPath']; ?>admin/editPoint.php?d="+dv+"&
newlat="+newlat+"newlng="+newlng+"&p="+p;
var s = $('mapStatus');
s.innerHTML = "EDiting Point...";
s.show();
new Ajax.Request(url, {
method: 'get',
onSuccess: editEntryReturn,
onFailure: requestFailed
});
}
editPoint.php
require("createThumb.php");
$newlng = $_GET['newlng'];
$newlat = $_GET['newlat'];
$p=$_GET['p'];
$q = "UPDATE entry SET lat = '$newlat', lng = '$newlng' WHERE id='$p';";
$r = updateBatch($q);
}
?>
but the position of the marker doesn't changes
Wrap your marker creation code in a function. This will create a closure in which the drag callbacks can find the appropriate marker object:
function createMarker (point)
{
var m = new GMarker(point,{draggable: true});
GEvent.addListener(m, "dragstart", function() {
var latlngold = m.getLatLng();
});
GEvent.addListener(m, "dragend", function() {
var latlngnew = m.getLatLng();
editentry1(latlngold,latlngnew);
});
return m;
}
Call this from inside your if statement after getting the point:
if (app.entries[id].data.lat != 0 || app.entries[id].data.lng != 0)
{
var point = new GLatLng(app.entries[id].data.lat,app.entries[id].data.lng);
map.addOverlay(createMarker (point));
}

Bing Maps - removing Itinery icons

I'm tryng to create a route planner to track my running routes. Using Bing Maps, I am able to create the route, but I'm struggling to remove to default 'beginning', 'end' and 'red circle' itinery icons.
Below is my code so far (based on this link). All I basically want is my own start icon at the beginning of the route and my end icon at the end. I don't need anything else in between apart from the route line.
Any help (along with code improvement tips) gratefully received!
jQuery(function() {
GetMap();
$("#btnStartRoute").click(function() {
map.AttachEvent('onclick', StartRouting);
});
});
var map = null;
var myRoute = [];
var noOfPushPins = 0;
function GetMap() {
map = new VEMap('mapContent');
map.SetCredentials("xxxxxxxxxxxxxxxxxx");
map.LoadMap();
}
function StartRouting(e) {
var xPoint = e.mapX, yPoint = e.mapY;
var pixel = new VEPixel(xPoint, yPoint);
var LL = map.PixelToLatLong(pixel);
cornerOne = LL; //cornerOne is a global level var
var latitude = map.PixelToLatLong(pixel).Latitude;
var longitiude = map.PixelToLatLong(pixel).Longitude;
myRoute[noOfPushPins] = new VELatLong(latitude, longitiude);
noOfPushPins++;
GetRoute();
}
function GetRoute() {
var myRouteOptions = new VERouteOptions();
myRouteOptions.RouteMode = VERouteMode.Walking;
myRouteOptions.RouteColor = new VEColor(0, 102, 51, .7);
myRouteOptions.RouteCallback = RouteCallback;
map.GetDirections(myRoute, myRouteOptions);
}
function RouteCallback(route) {
var myRouteShapes = [];
var myRoutePoints = [];
var points = route.RouteLegs[0].Itinerary.Items;
$.each(points, function(i) {
var routePointCoordinates = new VELatLong(route.RouteLegs[0].Itinerary.Items[i].LatLong.Latitude, route.RouteLegs[0].Itinerary.Items[i].LatLong.Longitude);
var routePointShape = new VEShape(VEShapeType.Pushpin, routePointCoordinates);
if (i != 0) {
routePointShape.SetCustomIcon("<img id='pushPin" + noOfPushPins + "' class='pushPin' src='/Content/Images/Maps/pushPinEnd.gif'><span class='pushPinText'>" + (noOfPushPins + 1) + "</span>");
} else {
routePointShape.SetCustomIcon("<img id='pushPin" + noOfPushPins + "' class='pushPin' src='/Content/Images/Maps/pushPinStart.gif'><span class='pushPinText'>" + (noOfPushPins + 1) + "</span>");
}
myRoutePoints.push(routePointShape);
map.Clear();
map.DeleteRoute();
map.AddShape(myRoutePoints);
});
}
There's an un-documented property called "Shape" on the Itinerary object. You can hide it...
More info here: http://social.msdn.microsoft.com/Forums/en/vemapcontroldev/thread/430449d0-fde4-4adb-9132-248fa6f9db65

Categories