Passing Two dimension array from vb.net to javascript - 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.

Related

Split values by comma separated string in javascript

Here is my issue:
I have RadListBox and I'm trying to get the values and append them so the result would be displayed like that: '1,2,3,4' but I'm getting back : 1,2,3,4,
Does anyone know how can I achieve that?
Problem starts here:
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ",");
}
The result: sbLocationsIDS =1,2,3,4, instead of '1,2,3,4'
The Rest of the Code:
function openNewTab(url) {
var captureURL = url;
var win = window.open(captureURL, '_blank');
win.focus();
}
function GetComparisonsReport(sender, args) {
var isValid = Page_ClientValidate('validateComparisons');
if (isValid) { // If its true is going to fire the rest of the code
var SessionID = getUrlVars()["SessionID"];
var companyCodeVal = document.getElementById("<%=hfC.ClientID%>").value;
var LocationIDS = $find("<%=rlbSelectedLocation.ClientID %>");
var CategoriesIDS = $find("<%=rlbSelectedCategory.ClientID %>");
var fileType = $find("<%=rcbFileType.ClientID %>");
var fromFirstPeriod = $find("<%=rdpFromFirstPeriod.ClientID %>");
var toFirstPeriod = $find("<%=rdpToFirstPeriod.ClientID %>");
var fromSecondPeriod = $find("<%=rdpFromSecondPeriod.ClientID %>");
var toSecondPeriod = $find("<%=rdpToSecondPeriod.ClientID %>");;
if (LocationIDS.get_items().get_count() < 0) {
radalert("Please choose locations and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
if (CategoriesIDS.get_items().get_count() < 0) {
radalert("Please choose categories and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
var fromFirstPeriodDateValSelected = fromFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toFirstPeriodDateValSelected = toFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fromSecondPeriodDateValSelected = fromSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toSecondPeriodDateValSelected = toSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fileTypeValSelected = fileType.get_selectedItem().get_value();
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ","); // The problem is here!!!
}
var sbCategoriesIDS = new StringBuilder();
for (i = 0; i < CategoriesIDS.get_items().get_count(); i++) {
sbCategoriesIDS.append(CategoriesIDS.getItem(i).get_value() + ",");
}
var ComparisonsURL = (String.format("https://www.test.com/cgis/{0}/reports/ConnectTorptIncidentsCountByLocationInterval.asp?SessionID={1}&locString={2}&catString={3}&FromDate1={4}&&ToDate1={5}&FromDate2={6}&ToDate2={7}&ExportType={8}", companyCodeVal, SessionID, sbLocationsIDS, sbCategoriesIDS, fromFirstPeriodDateValSelected, toFirstPeriodDateValSelected, fromSecondPeriodDateValSelected, toSecondPeriodDateValSelected, fileTypeValSelected));
openNewTab(ComparisonsURL);
}
}
String.format = function () {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value) {
this.strings = new Array("");
this.append(value);
}
// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value) {
if (value) {
this.strings.push(value);
}
}
// Clears the string buffer
StringBuilder.prototype.clear = function () {
this.strings.length = 1;
}
// Converts this instance to a String.
StringBuilder.prototype.toString = function () {
return this.strings.join("");
}
The problem is your loop is appending , always even for the last item in the loop.
You want to append only for all items other than the last. There are multiple ways to do that, simplest being: check if the current element is the last and if so, do not append ,
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()); //append only value
if(i != (LocationIDS.get_items().get_count() -1)) { //if not last item in list
sbLocationsIDS.append(","); //append ,
}
}
There are other ways to do it, and depending on what you want to do with the values in the future, these may be pretty useful. (I see that the append in your code is actually a call to join, so this is actually a simpler version)
Add the values of the list to a array and use Array.join:
var select = document.getElementById("locationId");
var options = select.options;
var optionsArray = [];
if(options) {
for (var i=0; i<=options.length; i++) {
//text is the text displayed in the dropdown.
//You can also use value which is from the value attribute of >option>
optionsArray.push(options[i].text);
}
}
var sbLocationsIDS = optionsArray.join(",");
With JQuery, the above code becomes a bit more simple:
var optionsArray = [];
$("#locationId option").each(function(){
optionsArray.push(options[i].text);
});
var sbLocationsIDS = optionsArray.join(",");
Actually, if you decide yo use JQuery, you can use jquery.map:
(idea from Assigning select list values to array)
$(document).ready(function() {
$("#b").click(function() {
var sbLocationsIDS = jQuery.map($("#locationId option"), function(n, i) {
return (n.value);
}).join(",");
alert(sbLocationsIDS);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="locationId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button id="b">Click</button>

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.

ArcGIS Javascript API - Polygon not showing up

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.

Reading the return value of a java script function with "evaluateJavaScript" from Qt

How to get a JavaScript function return value in C++?
After a long time of not using JavaScript, I implemented a route planner with the Google maps API V3. I defined some functions to access the scripting part of it via Qt's WebKit function: evaluateJavaScript(). Now the hard part is, to get the position data of the markers (see picture, markers are red). In the JavaScript end, I just return an array. How can I read the "latlng"-array in the Qt end?
Illustration - This is what I want simplified:
// JavaScript
function getJSFoo() {
return foofoo;
}
// C++
void readInQt() {
// something like this:
float val = evaluateJavaScript("getJSFoo()");
// Do stuff
}
Thanks in advance!
This my code, more or less how I use it.
At JavaScript's end:
// Add a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
draggable:true
});
var LatLng = marker.getPosition();
var sLatLng = "Latitude: " + marker.getPosition().lat().toString() +
"\nLongitude: " + marker.getPosition().lng().toString();
marker.setTitle(sLatLng);
flightMarker.push(marker);
return flightMarker;
}
function getMarkers() {
var latlng = []
for (var i = 0; i < flightMarker.length; i++) {
latlng.push(flightMarker[i].getPosition() );
}
return latlng;
}
At Qt's end:
void sl_submitRoute() {
getWaypoints();
}
QList<float> getWaypoints() {
QList<float> lWaypoints;
// I don't know what I do here :D
QVariant varMarkers = mView->page()->mainFrame()->evaluateJavaScript(QString("getMarkers();") );
QList <QVariant> allListObj = varMarkers.toList();
qDebug() << allListObj;
return lWaypoints;
}
I found the solution. Easiest way is to convert data into a QStringList and back.
Otherwise data type conversion could result in a leak.
JavaScript
function getMarkers() {
var latlng = []
for (var i = 0; i < flightMarker.length; i++) {
var sPos = flightMarker[i].getPosition().lat().toString() + ":" + flightMarker[i].getPosition().lng().toString();
latlng.push(sPos);
}
return latlng;
}
Qt
// Returns a list of points: Latitude & Longitude
RouteF getWaypoints() {
RouteF lWaypoints;
QVariant varMarkers = mView->page()->mainFrame()->evaluateJavaScript(QString("getMarkers();") );
QList<QVariant> allListObj = varMarkers.toList();
for(int i = 0; i < allListObj.size(); i++) {
QStringList lPoint = allListObj.at(i).toString().split(':');
if(lPoint.size() != 2) {
qDebug() << "Warning: Waypoint not valid!";
continue;
}
double fLat = lPoint.at(0).toDouble();
double fLon = lPoint.at(1).toDouble();
PointF waypoint = PointF(fLat, fLon);
lWaypoints.push_back(waypoint);
qDebug() << "Added point: " << fLat << ":" << fLon;
}
return lWaypoints;
}

Javascript : Using Switch to set variables values for the function

am totally new to Javascript , but i need it for using googlemaps in my project , am trying to set values for the latitude , longitude and map zoom for every certain city , so am getting the city name from a hidden form input and using Switch to switch regarding the city name .
cityDiv = document.getElementById('id_city');
cityDiv.value = idCity ;
switch (idCity)
{
case "city1":
var map_long = 31.37667;
var map_lat = 31.04306;
var map_zoom = 3;
break
case "city2":
var map_long = 31.33333;
var map_lat = 29.85;
var map_zoom = 7;
break
default:
var map_long = 31.37667;
var map_lat = 31.04306;
var map_zoom = 3;
}
function onLoad() {
map = new GMap(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.centerAndZoom(new GLatLng(map_lat,map_long) , map_zoom);
GEvent.addListener(map, 'click', function(overlay, point) {
if (prev_pin) {
map.removeOverlay(prev_pin);
prev_pin = null;
}
//var yPoint = new YGeoPoint({{ place.latitude }},{{ place.longitude }});
if (point) {
pin = new GMarker(point);
map.addOverlay(pin);
prev_pin = pin;
latDiv = document.getElementById('id_latitude');
lngDiv = document.getElementById('id_longitude');
lngDiv.value = point.x;
latDiv.value = point.y;
}
});
}
Sorry for this newbie question .
Best regards .
EDIT from comment by geowa4:
The question and the problem are The Variables never set :( , so whats wrong with my code ?! i change "cityDiv.value = idCity ; " to " var idCity = cityDiv.value ; " which didn't work as well but this time the map refuses to load
Try the code below:
mapInfo =
{
"city1":
{
"long": 31.37667,
"lat": 31.04306,
"zoom": 3
},
"city2":
{
"long": 31.33333,
"lat": 29.85,
"zoom": 7
}
};
function onLoad() {
map = new GMap(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var cityDiv = document.getElementById('id_city');
var idCity = cityDiv.value || "city1";
map.centerAndZoom(new GLatLng(mapInfo[idCity].lat,mapInfo[idCity].long) , mapInfo[idCity].zoom);
GEvent.addListener(map, 'click', function(overlay, point) {
if (prev_pin) {
map.removeOverlay(prev_pin);
prev_pin = null;
}
//var yPoint = new YGeoPoint({{ place.latitude }},{{ place.longitude }});
if (point) {
pin = new GMarker(point);
map.addOverlay(pin);
prev_pin = pin;
latDiv = document.getElementById('id_latitude');
lngDiv = document.getElementById('id_longitude');
lngDiv.value = point.x;
latDiv.value = point.y;
}
});
}
Have you tried dumping your values, stepping through and debugging? Alert statements, or console.log() statements, to see what the page thinks the value of that select is?
You might also consider making an object, that you can then update:
// Untested, but you should get the gist
var cityInfo = {
map_long : 0.0,
map_lat : 0.0,
map_zoom : 0
};
switch (idCity) {
case "city1":
cityInfo.map_long = 31.37667;
cityInfo.map_lat = 31.04306;
cityInfo.map_zoom = 3;
break
case "city2":
cityInfo.map_long = 31.33333;
cityInfo.map_lat = 29.85;
cityInfo.map_zoom = 7;
break
default:
cityInfo.map_long = 31.37667;
cityInfo.map_lat = 31.04306;
cityInfo.map_zoom = 3;
}
Your problem is scope, pure and simple. Using var scopes your variables to the current lexical scope, which in the case of var map_long = 31.37667; et al is the switch statement. Once you fall out of that scope, any variables declared in that scope vanish unless an external reference is maintained. You could remove the var statement, but that would make the variables global. I would recommend declaring your variables in a scope that makes sense to you, making them global only if absolutely necessary.

Categories