Elabel undefined error in Google Maps V3 - javascript

I have been porting a script I have from V2 to V3 and I have hit a snag. I am getting an Elabel undefined error but I am not sure why I am getting this. I have updated the Elabel.js to V3 which is here...ELABLE.JS I am not sure if this is not a good copy of ELabel.js or what. I have tried a couple of different other copies with no success.
Here is the working example of it using V2
V2 EXAMPLE
Here is the V3 example. As you can see in V3 the range rings are not drawn and the map doesn't update and the table doesn't populate. I know it is related to the ELabel.js but I am not sure why and I can't find the issue to why I am getting the undefined error. I know it is related to this because when I remove the script include for the ELable.js I have the same problems on V2 that I am seeing on V3.
V3 EXAMPLE
Since the code is too long to post here, the link to the relevant code is in the link below. Line 135 is where the ELabel error is coming from. This worked great in V2 but not V3. So I don't know if I am overlooking something that has changed in V2 to V3.
EXAMPLE CODE
So can anyone offer any insight on why I am getting this undefined error and shed some light on what I may be doing wrong and overlooking?
-Thanks

Texan, here's te script from my local file, which is working as far as getting the circles and labels to show. All ajax aspects are untested.
The script below should be pasted into the document head, immediately before the closing </head> tag.
This replaces various other inline scripts. The only remaining scripts in the document body should be the google analytics (2 scripts) and StatCounter (1 script). No external scripts should be removed.
<script>
var map;
jQuery(function($) {
var llCenter = new google.maps.LatLng(32.8297,-96.6486);
var URLToKML = 'http://www.mesquiteweather.net/NSGMap/GMStrikes.kml';
var Sec2Update = 30;
var KMLdate = 1372820133;
//var NSdate = 1372927434;
var NSdate = 0; //Force KML file creation on first update
var TZString = 'CDT';
var TZOffset = -5;
var nyLayer;
var lcolor = 'white';//This defines the line color for the target circle
//Check if user wants debug mode
dbg = (gup('dbg')=='y') ? 'y' : 'n';
var force = (gup('force')=='y') ? 'y' : 'n'; //Force updates regardless of NSStrikes.txt date
var mapReady = false;
function initialize() {
var mapOptions = {
center: llCenter,
panControl: false,
zoom: 6,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_TOP
},
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var radarOptions = {
gmap: map,
name: 'Radar',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function(){
if (map.overlayMapTypes.length==0) {
map.overlayMapTypes.push(null); // create empty overlay entry
map.overlayMapTypes.setAt("1", tileNEX);
}
else {
map.overlayMapTypes.clear();
}
}
}
var radarButton = new buttonControl(radarOptions);
tileNEX = new google.maps.ImageMapType({
getTileUrl: function(tile, zoom) {
return "http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-900913/" + zoom + "/" + tile.x + "/" + tile.y +".png?"+ (new Date()).getTime();
},
tileSize: new google.maps.Size(256, 256),
opacity: 0.70,
name: 'NEXRAD',
isPng: true
});
function MyLogoControl() {
var logo = $('<img/>').attr('src', 'images/watermark_MW_GMap.png').css('cursor', 'pointer').get(0);
google.maps.event.addDomListener(logo, 'click', function() {
window.location = 'http://www.mesquiteweather.net';
});
return logo;
}
var logoControlDiv = $('<div/>').css('padding','5px').append(MyLogoControl()).get(0);
logoControlDiv.index = 0; // used for ordering
map.controls[google.maps.ControlPosition.TOP_LEFT].push(logoControlDiv);
var nyLayer = new google.maps.KmlLayer(URLToKML + "?rand=" + (new Date()).valueOf(), {
suppressInfoWindows: false,
map: map,
preserveViewport: true
});
google.maps.event.addListenerOnce(map, 'idle', function() {
//You can add circles, or change other parameters
//radials should be set to true for the maximum distance if you want radials
//doDrawCircle(circleUnits, center, circleRadius, lineColor, lineWidth, lineOpacity, fillColor, fillOpacity, opts, radials)
doDrawCircle('MI', llCenter, 62, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 124, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 187, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 249, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 312, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 374, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
//doDrawCircle('MI', llCenter, 374, lcolor, 1, .7, '#00FF00', 0, { clickable: false }, true); // This would add the radials
UpdateKML();//Get the first set of data
});
}
//Function to draw circles
function doDrawCircle(circleUnits, center, circleRadius, liColor, liWidth, liOpa, fillColor, fillOpa, opts, radials) {
var polyLineOptions = {
map: map,
path: null,//added with jQuery.extend()
strokeColor: liColor,
strokeOpacity: liOpa,
strokeWeight: liWidth
};
var bounds = new google.maps.LatLngBounds();
var circlePoints = [];
var d = circleRadius / ((circleUnits == 'KM') ? 6378.8 : 3963.189);
var d2r = Math.PI/180;
var lat1 = d2r * center.lat();//radians
var lng1 = d2r * center.lng();//radians
for (var a=0; a<361; a++ ) {
var tc = d2r * a;
var sin_lat1 = Math.sin(lat1),
cos_lat1 = Math.cos(lat1),
sin_d = Math.sin(d),
cos_d = Math.cos(d),
sin_tc = Math.sin(tc),
cos_tc = Math.cos(tc);
var y = Math.asin(sin_lat1 * cos_d + cos_lat1 * sin_d * cos_tc);
var dlng = Math.atan2(sin_tc * sin_d * cos_lat1, cos_d - sin_lat1 * Math.sin(y));
var x = ((lng1 - dlng + Math.PI) % (2 * Math.PI)) - Math.PI ; // MOD function
var point = new google.maps.LatLng(y/d2r, x/d2r);
circlePoints.push(point);
bounds.extend(point);
if(a==0) {
var offset = new google.maps.Size((circleRadius < 100) ? -5 : -8, 0);
//ELabel(map, point, html, classname, pixelOffset, percentOpacity, isFloatShadow, overlap);
var label = new ELabel(map, point, circleRadius, "style1", offset, 100, false);
label.setMap(map);
}
if (radials && ((a==0) || (a==45) || (a==90) || (a==135) || (a==180) || (a==225) || (a==270) || (a==315))) {
new google.maps.Polyline($.extend({}, polyLineOptions, {
path: [center, point]
}));
}
}
new google.maps.Polyline($.extend({}, polyLineOptions, {
path: circlePoints
}));
map.fitBounds(bounds);//This sets the map bounds to be as big as the target circles, comment out if you don't want it
}
//This function is called on page load to start the refresh of the strikes
function cycle() {
setInterval(CountDown, 1000);
}
var intvl = Sec2Update;
function CountDown() {
intvl -= 1;
if(intvl < 1) {
intvl = Sec2Update;
UpdateKML();
}
$("#cntdwn").html(intvl);
}
//This calls genkml.php on every refresh cycle to generate a new kml file
function UpdateKML() {
$.ajax({
url: 'genkml.php',
type: "GET",
data: {
force: force,
ofd: KMLdate,
nsd: NSdate,
dbg: dbg
},
cache: false,
dataType: '',//????
}).done(function(resp, textStatus) {
var $debugDiv = $("#div1");
if (dbg == 'y') {//Check if we want debug info
if (!$debugDiv.length) {//Check if debug div exists, if not add it to end of body
$debugDiv = $("<div/>").attr('id', 'div1').appendTo('body');
}
var tmpresp = resp || ' ';
$debugDiv.html('Response Status: ' + textStatus + '<br />' + tmpresp);
} else {//Else empty the debug div
$debugDiv.empty();
}
var dates = resp.split("|")[0].split("~");
KMLdate = dates[0];
NSdate = dates[1];
updateHTML(resp);//This calls the updateHTML function if info was returned
});
if(map) {
if(nyLayer) {
map.removeOverlay(nyLayer); //Remove overlays
}
//nyLayer = new KmlLayer(URLToKML + "?rand="+(new Date()).valueOf() );
nyLayer = new google.maps.KmlLayer(URLToKML + "?rand=" + (new Date()).valueOf(), {
suppressInfoWindows: false,
map: map,
preserveViewport: true
});
}
// Time overlayed on map - could be in updateHTML() to just show when .kml read last
$('#currenttime').innerHTML = CurrentTime ("B", "12a", true, TZOffset);
}
function CurrentTime (type, hours, secs, ofs) {
/*
type (char) hours (char) secs (bool) ofs (num)
"U"-UTC "24"=24 hr time true=hh:mm:ss 0=hours from UTC
"B"-User's Browser "12"=12 hr time false=hh:mm
"S"-Web Site "12a"=am/pm
*/
if (type == null){ type = "B"; } // These are the defaults
if (hours == null){ hours = "12a"; }
if (secs == null){ secs = true; }
if (ofs == null){ ofs = 0; }
var currentHour = 0;
var currentMinute = 0;
var currentSecond = 0;
var time = [];
var currentDate = new Date();
if (type == "U") {
currentHour = currentDate.getUTCHours();// UTC
} else if (type == "B") {
currentHour = currentDate.getHours();// Viewer's time
} else {
currentHour = currentDate.getUTCHours() + ofs;// your local time
if(currentHour < 0) { currentHour = currentHour + 24;}
}
currentMinute = currentDate.getMinutes();
currentMinute = (currentMinute < 10 ? "0" : "") + currentMinute;
if (hours == "24") {
if(currentHour == 24) { currentHour = 0 };// use if wanting 24 hour time
currentHour = (currentHour < 10 ? "0" : "") + currentHour;
} else if (hours == "12") {
if(currentHour == 0) currentHour = 12;
currentHour = (currentHour < 10 ? "0" : "") + currentHour;
} else {
if(currentHour == 0) currentHour = 12;// else no leading zero for am/pm
}
time.push(currentHour, currentMinute);
if (secs) {
currentSecond = currentDate.getSeconds();
currentSecond = (currentSecond < 10 ? "0" : "") + currentSecond;
time.push(currentSecond);
}
time = time.join(' : ');
if(hours == "12a") {
time = time + " " + (currentHour > 12 ? "PM" : "AM");
}
return time;
}
//This function is only used if you leave the debug checkbox below
// You can remove this function and the checkbox and set the debug
// mode using the dbg=y query parameter
function debug(obj){
if (obj.checked) {
dbg = 'y';
} else {
dbg = 'n';
$('#div1').empty();
}
}
//This function is only used if you leave the Force Update checkbox below
// You can remove this function and the checkbox and set the force
// mode using the force=y query parameter
function forceupdate(obj) {
force = (obj.checked) ? 'y' : 'n';
}
//This function parses out the query parameter value
function gup( name ) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
return results ? results[1] : "";
}
/*
You can add custom HTML code here and get access to the additional data that is returned everytime the page calls genkml.php.
In the example below, result is an array that holds 16 values (17, if in debug mode) with each of the values explained below.
*/
function updateHTML(resp) {
var result = resp.split("|");
if (result.length < 16) return;//Make sure there is data
document.getElementById('q1').innerHTML = result[1];//Number of strikes in first quarter of diplay time
document.getElementById('q2').innerHTML = result[2];//Number of strikes in second quarter of diplay time
document.getElementById('q3').innerHTML = result[3];//Number of strikes in third quarter of diplay time
document.getElementById('q4').innerHTML = result[4];//Number of strikes in fourth quarter of diplay time
document.getElementById('numicp').innerHTML = result[6];//Number of IC+ strikes
document.getElementById('numicn').innerHTML = result[5];//Number of IC- strikes
document.getElementById('numcgp').innerHTML = result[7];//Number of CG+ strikes
document.getElementById('numcgn').innerHTML = result[8];//Number of CG- strikes
document.getElementById('ds').innerHTML = result[9];//Total displayed strikes
document.getElementById('ta').innerHTML = result[10];//Total strikes in NSStrikes
document.getElementById('dt').innerHTML = result[11];//Display time
document.getElementById('numicpd').innerHTML = result[13];//Number of IC+ strikes
document.getElementById('numicnd').innerHTML = result[12];//Number of IC- strikes
document.getElementById('numcgpd').innerHTML = result[14];//Number of CG+ strikes
document.getElementById('numcgnd').innerHTML = result[15];//Number of CG- strikes
document.getElementById('tu').innerHTML = Date();//Number of CG- strikes
document.getElementById('sec2up').innerHTML = Sec2Update;//Number of CG- strikes
var dt = result[11] / 4;
document.getElementById('q1t').innerHTML = [0, dt].split('-');//Set time frame headers
document.getElementById('q2t').innerHTML = [dt, 2*dt].split('-');
document.getElementById('q3t').innerHTML = [2*dt, 3*dt].split('-');
document.getElementById('q4t').innerHTML = [3*dt, dt].split('-');
}
//Onload event caller. Does not intefere with OnLoad event in Body tag.
//Put this is after all functions to be called
function addLoadEvent(func) {
$(window).on('load', func);
}
initialize();
FADING_SCROLLER.changecontent();
});
</script>
<script type="text/javascript">
/***********************************************
* Fading Scroller- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************
* Wrapped as module by Beetroot-Beetroot
* Converted to use jQuery calls by Beetroot-Beetroot
* Note: The "proper" approach would be to use the 'color' jQuery plugin
***********************************************/
var FADING_SCROLLER = (function($) {//Module patttern
var delay = 5000; //set delay between message change (in miliseconds)
var maxsteps = 10; //number of steps to take to change from start color to endcolor
var stepdelay = 200; //time in miliseconds of a single step
//**Note: maxsteps*stepdelay will be total time in miliseconds of fading effect
var startcolor = [201,201,201]; //start color (red, green, blue)
var endcolor = [0,0,0]; //end color (red, green, blue)
var fadelinks = 1; //should links inside scroller content also fade like text? 0 for no, 1 for yes.
// *** No need to edit below this line ***
var faderdelay = 0;
var index = 0;
function changecontent() {
var $fscroller = $("#fscroller").css('color', "rgb(" + startcolor.join(', ') + ")");
var $content = $fscroller.find(".NWSinfo div").hide().eq(index).show().end();
if(fadelinks) linkcolorchange(1);
colorfade(1, 15);
index = (index + 1) % $content.length;
}
function linkcolorchange(step) {
$("#fscroller a").each(function() {
$(this).css('color', getstepcolor(step));
});
}
// Rafael Raposo edited function
var fadecounter;
function colorfade(step) {
if(step<=maxsteps) {
$("#fscroller").css('color', getstepcolor(step));
if (fadelinks)
linkcolorchange(step);
step++;
fadecounter = setTimeout(function() {
colorfade(step);
}, stepdelay);
} else {
clearTimeout(fadecounter);
$("#fscroller").css('color', "rgb(" + endcolor.join(', ') + ")");
setTimeout(changecontent, delay);
}
}
//Rafael Raposo's new function
function getstepcolor(step) {
var diff, newcolor = [];
for(var i=0; i<3; i++) {
diff = startcolor[i] - endcolor[i];
if(diff > 0) {
newcolor[i] = startcolor[i] - (Math.round((diff/maxsteps)) * step);
} else {
newcolor[i] = startcolor[i] + (Math.round((Math.abs(diff)/maxsteps)) * step);
}
}
return "rgb(" + newcolor.join(', ') + ")";
}
// *** Expose public methods here ***
return {
changecontent: changecontent
};
})(jQuery);
</script>
I only changed the javascript, not the CSS or HTML. Some comments are included but not really enough considering the scope of the changes.
You will see I wrapped the main script in a $(function(){...}) structure and the Fading Scroller script as a Module. This was done to prevent polluting the global namespace and the possibility of contamination between scripts. I left map in the global namespace in case it's needed in any of the other scripts.
I also made some changes to a local copy of ajaxWDwx.js but I don't think any of them are relevant.

Related

getBoundingClientRect of SVG Path not working

I am making a library for Google Geo Charts on click zooming (API != zoom)
I need to get the width or height of the svg paths so I can filter them and store their coordinates in an array object. I was able to store alaska and hawaii g elements coords but with the continental US I have to go one level deeper to path and am having a hard time realizing where I am going wrong.
I am getting undefined on the continental nodeList.
google.visualization.events.addOneTimeListener(chart, 'ready', function (e){
google.visualization.events.addListener(chart, 'select', function (e){
var selection = chart.getSelection(),
selectedState = '',
nodes = document.querySelectorAll("g[clip-path]")[0].childNodes[0],
continental = nodes.childNodes[0],
alaska = nodes.childNodes[1],
hawaii = nodes.childNodes[2],
stateCoords = {},
nl = null,
zoomX = null,
zoomY = null;
//////////////////////////////
//Get Coordinates of States//
/////////////////////////////
getCoords(alaska);
getCoords(hawaii);
// getCoords(continental);
console.log(stateCoords);
function getCoords(nodeList){
function getZoom(nodeList, s){
nl = nodeList.getBoundingClientRect();
zoomY = nl.top + (nl.height/2);
zoomX = nl.left + (nl.width/2);
stateCoords[s] = [zoomX, zoomY];
}
if (nodeList == alaska) {
getZoom(nodeList, 1);
}
else if (nodeList == hawaii){
getZoom(nodeList, 11);
}
else {
console.log('continental');
var nodeListLength = nodeList.childNodes.length,
i = 0,
s = 0;
for (i; i < nodeListLength; i++) {
console.log(nodeList.childNodes[i]);
var pathBound = nodeList.childNodes[i].getBoundingClientRect();
if (pathBound.height > 3 && s != 1 && s!= 11) {
getZoom(nodeList[i], s);
s++;
} else { s++; }
}
}
}

I am trying to plot a race time "01:23:22" on a chart with Flot and so i can compare over time

I am writing an App that tracks swimmers race results based on date and time
The data set will look similar to this (Date, RaceTime)
var results = [
['12/01/2015', '02:05:00'],
['12/08/2015', '01:15:00'],
['12/15/2015', '04:20:00']
];
I am using the following code to try and plot it, but I cannot get accurate plots and tooltip is wrong.
<script>
$(document).ready(function(){
var originalData = [
['12/01/2015', '02:05:00'],
['12/08/2015', '01:15:00'],
['12/15/2015', '04:20:00']
];
var data = [];
var test = [];
for (var i = 0; i < originalData.length; i++) {
var dataPoint = [];
dataPoint.push((new Date(originalData[i][0])));
var time = originalData[i][1].split(':');
var hours = parseInt(time[0]);
var minutes = parseInt(time[1]);
var seconds = parseInt(time[2]);
dataPoint.push(hours + minutes + seconds /60);
data.push(dataPoint);
}
var options = {
series: {
lines: {
show: true
},
points: {
show: true
}
},
xaxis: {
mode: 'time',
timeformat: "%0m/%0d %0H:%0M",
tickSize: [5, 'week']
},
yaxis: {
min: 0,
max: 24
},
grid: {
hoverable:true,
clickable:true
}
};
var plot = $.plot("#placeholder"
,[data], options);
var previousPoint = null;
$("#placeholder").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.datapoint) {
previousPoint = item.datapoint;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2)
showTooltip(item.pageX, item.pageY,
y);
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
border: '1px solid #fdd',
padding: '2px',
'background-color': '#fee',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
});
</script>
My goal is to plot the 3 values so that I can see the differences in the swimmers times
The code
dataPoint.push(hours + minutes + seconds /60);
is messing things up and not working as I intended.
Any help would be appreciated
Your code dataPoint.push(hours + minutes + seconds /60); treats hours and minutes the same which leads to errors. If you want to display the race time in minutes, use 60*hours + minutes + seconds/60 (if you want it in hours use hours + minutes/60 + seconds/3600).
To get the original formatted race time back from the race time in minutes, use something like this:
function getFormattedTime(timeInMinutes) {
var hours = Math.trunc(timeInMinutes / 60);
var minutes = Math.trunc(timeInMinutes % 60);
var seconds = Math.round(60 * (timeInMinutes - Math.round(timeInMinutes)));
var result = hours.toString() + ':';
result += (minutes < 10 ? '0' : '') + minutes.toString() + ':';
result += (seconds < 10 ? '0' : '') + seconds.toString();
return result;
}

Google Map API throwing JS error

Trying to animate a line and I have figure out most of the code. I am getting an error and not sure why?
Here is error logged into the console. You can see where it goes wrong.
CONSOLE LOG:
c is (30.37470457, -97.76039932000003)
get at depature is (30.37470457, -97.76039932000003)
get at arrival is (30.39386213, -97.75522519000003)
path is path.getPath() [object Object]
steps is running
are we there yet is(30.374781200646034, -97.76037862752048)
steps is running
js?key=secret&sensor=false&libraries=geometry:38 Uncaught TypeError: Cannot read property 'lat' of undefined_.Ob # js?key=secret&sensor=false&libraries=geometry:38Gy.interpolate # js?key=secret&sensor=false&libraries=geometry:125(anonymous function) #
steps is running
js?key=secret&sensor=false&libraries=geometry:38 Uncaught TypeError: Cannot read property 'lat' of undefined_.Ob # js?key=secret&sensor=false&libraries=geometry:38Gy.interpolate # js?key=secret&sensor=false&libraries=geometry:125(anonymous function) #
steps is running
js?key=secret&sensor=false&libraries=geometry:38 Uncaught TypeError: Cannot read property 'lat' of undefined_.Ob # js?key=secret&sensor=false&libraries=geometry:38Gy.interpolate # js?key=secret&sensor=false&libraries=geometry:125(anonymous function) #
steps is running
JS CODE:
function drawPath2(run_id){
var request = $.ajax({
url: "/requester/potrip?r_id=" + r_id,
type: "GET",
dataType: "json"
});
request.done(function(data) {
console.log("starting request done");
var p = data['points'];
var c = [];
var bounds = new goog.LatLngBounds();
for(var i = 0; i < p.length; i++){
var l = new goog.LatLng(parseFloat(p[i][1]), parseFloat(p[i][0]));
bounds.extend(l);
c.push(l);
}
console.log("c is " + c);
console.log("c is " + c[0]);
departure = parseFloat(c[0][1]);
arrival = parseFloat(c[c.length-1][0]);
var path = createPoly(c, "head");
map.fitBounds(bounds);
path.setMap(null);
console.log("get at depature is " + path.getPath().getAt(0));
console.log("get at arrival is " + path.getPath().getAt(path.getPath().getLength()-1));
console.log("path is path.getPath() " + path.getPath());
var step = 0;
var numSteps = 250; //Change this to set animation resolution
var timePerStep = 5; //Change this to alter animation speed
var theLenght = path.getPath().getLength()-1;
var interval = setInterval(function() {
step += 1;
console.log("steps is running");
if (step > numSteps) {
console.log("clearinginterval" + step);
clearInterval(interval);
} else {
var are_we_there_yet = google.maps.geometry.spherical.interpolate(path.getPath().getAt(0),path.getPath().getAt(1),step/numSteps);
console.log("are we there yet is" + are_we_there_yet);
path.setPath([path.getPath().getAt(0), are_we_there_yet]); <-- ERROR
}
}, timePerStep);
});
request.fail(function(jqXHR, textStatus) {
console.log( "Request failed: " + textStatus );
});
}
UPDATE:
After using #geocodezip answer and code I had several syntax issues. I am using his code now, but still not working. I believe it is my data points that are the issue. My points are plots from 3 seconds GPS grabs, not just the begginging and end points. I have updated #geocodezip JSFiddle and you can see when using my data points it draws one dot. If you delete all my data points, but two then it draws a line, but not on the data points I have.
https://jsfiddle.net/rpse4u7q/7/
DATA:
var data = {
"points": [
[-97.76039932, 30.37470457],
[-97.76039773, 30.37470464],
[-97.76025161, 30.37481161],
[-97.76048998, 30.3752743],
[-97.76086747, 30.37543242],
[-97.76218839, 30.3757006],
[-97.76345371, 30.37628355],
[-97.76440906, 30.37738785],
[-97.76498148, 30.37882327],
[-97.76550885, 30.38187354],
[-97.76606298, 30.38390495],
[-97.76639823, 30.38462131],
[-97.76633701, 30.38513405],
[-97.7652047, 30.38599167],
[-97.76364974, 30.38714456],
[-97.76177313, 30.38802739],
[-97.76056218, 30.38809251],
[-97.76013834, 30.38807344],
[-97.75972944, 30.38843747],
[-97.75970029, 30.38948685],
[-97.75958011, 30.39068898],
[-97.75859334, 30.39140352],
[-97.75722475, 30.39161915],
[-97.75636673, 30.3926098],
[-97.75564576, 30.39375132],
[-97.75525439, 30.39416341],
[-97.75484361, 30.39382476],
[-97.75508556, 30.39377933],
[-97.75523972, 30.39385163],
[-97.75522519, 30.39386213]
]
}
var olddata = {
points: [
[-72, 42],
[-73, 43]
]
};
You have a logic issue. You can't use the path of the polyline to contain the final value of the path and the interpolated value. Once you have run the animation once it gets stuck at a zero length polyline.
This code works for me:
var are_we_there_yet = google.maps.geometry.spherical.interpolate(
c[0],
c[1],
step / numSteps);
path.setPath([c[0], are_we_there_yet]);
code snippet:
var map;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
animatePolyline(data);
}
google.maps.event.addDomListener(window, "load", initialize);
function animatePolyline(data) {
// input data
var p = data.points;
// array of google.maps.LatLng objects
var c = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < p.length; i++) {
var l = new google.maps.LatLng(parseFloat(p[i][1]), parseFloat(p[i][0]));
bounds.extend(l);
c.push(l);
}
var path = new google.maps.Polyline({
path: [],
map: map
});
map.fitBounds(bounds);
path.setMap(map);
var step = 0;
var numSteps = 250; //Change this to set animation resolution
var timePerStep = 5; //Change this to alter animation speed
var theLength = path.getPath().getLength() - 1;
var interval = setInterval(function() {
step += 1;
if (step > numSteps) {
clearInterval(interval);
} else {
var are_we_there_yet = google.maps.geometry.spherical.interpolate(c[0], c[1], step / numSteps);
path.setPath([c[0], are_we_there_yet]);
}
}, timePerStep);
}
var data = {
points: [
[-72, 42],
[-73, 43]
]
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map_canvas"></div>

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.

Categories