I have the program below that reads aircraft coordinates from a txt file and places a number of markers on Google Maps. Every 2 sec it reads the txt file again and pushes the markers to the new aircraft locations. This works fine with the original markers "moving" to the new positions. What I would like to do is add a label to the marker to show the height of each aircraft. To do this I need to generate the label after the txt file has been read but when I do it doesn't delete the old markers but adds new markers.
The portion of code below is working fine but without a variable labels. The relevant code is where var eplanezero is created. If I move this line of code anywhere within the setInterval(function (){ the eplanezero.setPosition will not function properly. I have tried dozens of various but nothing seems to work. Any thoughts appreciated. Note that this is only a portion of the code.
moveMarker(map, playerIcon, enemyIcon);
}
function moveMarker(map, playerIcon, enemyIcon)
{
var eplanezero = new google.maps.Marker({map: map, icon: enemyIcon, label: "1"});
setInterval(function ()
{
$.post("MISSION_ADMIN_radar.txt", function(dataenemy, status)
{
var latlnge = JSON.stringify(dataenemy);
latlnge = latlnge.replace(/"/g,"");
latlnge = latlnge.replace(/[\\r\\n]/g,"");
CoordsEnemy = latlnge.split(";");
var army = parseFloat(CoordsEnemy[0].substring(0));
if (army == 2)//Own army = 1, Enemy = 2
{
var commaPos = CoordsEnemy[0].indexOf(',');
var hyphenPos = CoordsEnemy[0].indexOf('+');
var lat0 = parseFloat(CoordsEnemy[0].substring(4, commaPos));
var long0 = parseFloat(CoordsEnemy[0].substring(commaPos + 1, CoordsEnemy[0].length));
}
eplanezero.setPosition(new google.maps.LatLng(lat0, long0));
});
}, 2000);
The altitude is obtained from the same array that holds the lat and long. However, to place the variable Alt into the marker, I have to create variable eplanezero in the setInterval function so that it updates it every 2 secs. When I do this, it will not move the marker but adds a new marker, leaving the original marker in the old position.
The revised code is as follows:
function moveMarker(map, playerIcon, enemyIcon)
{
//var eplanezero = new google.maps.Marker({map: map, icon: enemyIcon, label: "1"});
var eplanezero = new google.maps.Marker({map: map, icon: enemyIcon, label: Alt});
setInterval(function ()
{
$.post("MISSION_ADMIN_radar.txt", function(dataenemy, status)
{
var latlnge = JSON.stringify(dataenemy);
latlnge = latlnge.replace(/"/g,"");
latlnge = latlnge.replace(/[\\r\\n]/g,"");
CoordsEnemy = latlnge.split(";");
var army = parseFloat(CoordsEnemy[0].substring(0));
if (army == 2)//Own army = 1, Enemy = 2
{
var commaPos = CoordsEnemy[0].indexOf(',');
var hyphenPos = CoordsEnemy[0].indexOf('+');
var Alt0 = parseFloat(CoordsEnemy[0].substring(hyphenPos + 1 , CoordsEnemy[0].length));
var lat0 = parseFloat(CoordsEnemy[0].substring(4, commaPos));
var long0 = parseFloat(CoordsEnemy[0].substring(commaPos + 1, CoordsEnemy[0].length));
var eplanezero = new google.maps.Marker({map: map, icon: enemyIcon, label: Alt});
}
eplanezero.setPosition(new google.maps.LatLng(lat0, long0));
});
}, 2000);
.setPosition must be a method that looks in the array and checks for previous coordinates. if the array doesn't contain any coordinates it places a new marker at the new coordinates, If the array does contain coordinates it "moves"the marker to the new location. Establishing the array within the loop deletes any previous array and the coordinates and therefore Google Map correctly places a new marker. Only by creating the array outside the loop will the method work correctly. Unfortunately this means that the label or the icon cannot be changed once the array is created.
Related
I have been reading and researching how to animate overlays. I Haven't found anything related to what I am looking for. Mostly it was related to markers. I have an overlay I apply like this and it works great.
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.60,
name: 'NEXRAD',
isPng: true
});
The source for the data also offers 10 other past images. So I would like to create an animated loop with those feeds. Is this option available in V3 as I have read some conflicts with doing this. I mean it must be possible because I have seen others with it. How would I go about loading the multiple layers then animating them?
-Thanks!
I know this is old but I hope this helps someone else looking for the same thing. This probably isn't the most elegant solution but it got the task done. I simply map over the predefined image urls creating my ImageMapTypes and then pass that into an animation loop which checks to see if there is a layer on the map, clears if it there is and then sets the new layer based on a loop count. Hope this helps.
var map;
// Weather tile url from Iowa Environmental Mesonet (IEM): http://mesonet.agron.iastate.edu/ogc/
var urlTemplate = 'http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-{timestamp}/{zoom}/{x}/{y}.png';
// The time stamps values for the IEM service for the last 50 minutes broken up into 5 minute increments.
var timestamps = ['900913-m50m', '900913-m45m', '900913-m40m', '900913-m35m', '900913-m30m', '900913-m25m', '900913-m20m', '900913-m15m', '900913-m10m', '900913-m05m', '900913'];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 38.0781, lng: -97.7030},
zoom: 5
});
let tileSources = timestamps.map((timestamp) => {
return new google.maps.ImageMapType({
getTileUrl: function(tile, zoom) {
const { x, y} = tile;
return `https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-${timestamp}/${zoom}/${x}/${y}.png?`+ (new Date()).getTime();
},
tileSize: new google.maps.Size(256, 256),
opacity:0.60,
name : 'NEXRAD',
isPng: true
});
});
startAnimation(map, tileSources);
}
function startAnimation(map, layers) {
// create empty overlay entry
map.overlayMapTypes.push(null);
var count = 0;
window.setInterval(() => {
if(map.overlayMapTypes.getLength() > 0)
map.overlayMapTypes.clear();
map.overlayMapTypes.setAt("0",layers[count]);
count = (count + 1) % layers.length;
},800);
}
I am using phonegap, jquerymobile the googlemap API to get my current position and to watch my position.
For this, when I lunch my map page, my position is shown with a marker and the marker move when I move.
Even if it works excpeted when I close my App (onPause).
Here is my code (you can tell me how I can perfect it :o) )
$('#home').live("pagebeforeshow", function() {
if($('#googleAPI').length != 0){
navigator.geolocation.getCurrentPosition(function(position){
//showMap('mapHome',position.coords.latitude, position.coords.longitude);// Canvas, lat, long
var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
// Google Map options
var myOptions = {
zoom: 17,
//zoomControl : 1,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP////ROADMAP, SATELLITE, HYBRID and TERRAIN
};
// Create the Google Map, set options
Tracking.mapy = new google.maps.Map(document.getElementById('mapHome'), myOptions);
//addMarker(position.coords.latitude,position.coords.longitude);
},
showError,
{
enableHighAccuracy : true,
maximumAge : 2000
//maximumAge:Infinity
});
}
})
$('#home').live("pageshow", function() {
// Place and move the marker regarding to my position and deplacement
if($('#googleAPI').length != 0){
//var track_id = "me";
Tracking.watch_id = navigator.geolocation.watchPosition(
// Success
function(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latLng = new Array();
latLng[0] = lat;
latLng[1] = long;
//Tracking.myCoordinates.push(lat,long);
Tracking.myCoordinates.push(latLng);
addMarker(lat, long);
},
// Error
showError,
{
frequency: 1000
});
console.log('HW : WatchPosition called. Id:' + Tracking.watch_id);
}else{
Alert.show('The map API has not been loaded. Check for connection and try again. (pagebeforeshow)');
}
})
$('#home').live("pagebeforehide", function() {
if($('#googleAPI').length != 0){
//track_id = "me";
// Stop tracking the user
if (Tracking.watch_id != null) {
navigator.geolocation.clearWatch(Tracking.watch_id);
console.log('HW : WatchPosition cancelled Id:' + Tracking.watch_id);
Tracking.watch_id = null;
}
//navigator.geolocation.clearWatch(Tracking.watch_id);
//Tracking.watch_id = null;
Tracking.myCoordinates = new Array();
}else{
Alert.show('The map API has not been loaded. Check for connection and try again. (pagebeforeshide)');
}
});
The problem is when I close my App, because I still need to be alert when I go outside of my geofence. Then, as lomg as I do not stop to watch my position, I need it to be watching even if I close my position or if I lunch another app.
Then I do not know how to do when I called that Phonegap even:
document.addEventListener('pause', onPause, false);
function onPause(){}
Should I simply relunch my watch code with a different watch_id?
Any suggestion?
Many thank and happy new year
I think what you're trying to get at is running a background process using phonegap. The discussion in this link seems to say that it's only possible if you write a plugin to perform that functionality. PhoneGap doesn't have an API to do it out of the box.
Executing javascript in background using phonegap
I have to create several markers on Google Maps, in run-time.
Their initial position is randomly defined.
When they are created, how can I change position of some of them? New position is also randomly defined.
I did tried with
marker1.setPosition(pt);
... but, I'm getting error
marker1 is not defined
I guess that problem is that marker1 is not defined in moment when map is created... Something like that.
Can you help me how can I solve this one?
p.s. There is no limit of how many markers will be created.
UPDATE Markers are created with:
function addNewMarker( locationsTotal ) {
if (document.getElementById("lon1").value == '') document.getElementById("lon1").value = '19';
if (document.getElementById("lat1").value == '') document.getElementById("lat1").value = '45';
var parliament = (map.getCenter());
var newMarker = 'marker' + locationsTotal;
newMarker = new google.maps.Marker({
name:newMarker,
id:newMarker,
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: parliament,
icon: 'img/pin.png'
});
google.maps.event.addListener(newMarker, "dragend", function() {
var center = newMarker.getPosition();
var latitude = center.lat();
var longitude = center.lng();
var newLon = 'lon' + locationsTotal;
var newLat = 'lat' + locationsTotal;
document.getElementById(newLon).value = longitude;
document.getElementById(newLat).value = latitude;
});
}
As You can see newMarker is visible only in the scope of addNewMarker function.
What you need is to store your markers in array visible in global scope.
For example:
Modify your function:
var allMarkers = [];
function addNewMarker( locationsTotal ) {
//.... skip
allMarkers.push(newMarker);
}
All your markers are now stored in an array so you can manipulate them.
To access marker by name add function:
function getMarker(name) {
for (k in allMarkers)
if (allMarkers[k].name == name) return allMarkers[k];
return null;
}
I'm trying to get specific variables out of a for each loop. These variables are used to display a click event on a marker on a map. If you click the marker on the map, the details pop over it. Now these details are being overwritten each time the loop starts (50 times). The solution I'm looking for, let's me select a marker on the map with the according detail attached to it.
There might be an easy solution but I haven't found it yet.
The code :
for each(artistXML in artistList.events.event)
{
var gLat:int = artistXML.venue.location.*::point.*::lat;
var gLong:int = artistXML.venue.location.*::point.*::long;
var evntLng:LatLng = new LatLng(gLat,gLong);
var title:String = artistXML.title;
var wanneer:String = artistXML.startDate;
var waar:String = artistXML.venue.location.city;
var pic:String = artistXML.venue.image.(#size=="medium");
var marker:Marker = new Marker(new LatLng(gLat, gLong));
var info:InfoWindowOptions = new InfoWindowOptions();
marker.addEventListener(MapMouseEvent.CLICK, function(event:Event):void {
var marker:Marker = event.target as Marker;
marker.openInfoWindow(new InfoWindowOptions({contentHTML: "<p><b>" + title + "</b></p><br/><p>" + wanneer + "</p> <br/> <p>" + waar + "</p>"}));
});
map.addOverlay(marker);
Goverlay++;
}
Thanks
You need to store a reference to the values somewhere before you start the next loop.
I'm not sure what the structure of your Marker and InfoWindowOptions classes are, so there might be a better way, but here's a naive solution:
Create 2 arrays called mapMarkers and infoWindows. For each loop push the new Marker and the new InfoWindowOptions instances into the appropriate arrays. You'll need to set those variables on the InfoWindowOptions too. Then in your click handler you can lookup the index of the Marker that was clicked (mapMarkers.indexOf(marker)) and use that index to get the corresponding InfoWindowOptions.
So this gets auto generated through the controller and I think I'm just overlooking something but the output is just like this
google.load("maps", "2.x", {"language" : "en"});
function initialize() {
if (GBrowserIsCompatible()) {
// Initialize the GMap
var map = new google.maps.Map2(document.getElementById("map"));
map.addControl(new google.maps.SmallMapControl());
map.setCenter(new google.maps.LatLng(30.226632, -97.935056), 10, G_NORMAL_MAP);
// Build custom marker icons
var tinyIcon = new google.maps.Icon();
tinyIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
tinyIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
tinyIcon.iconSize = new google.maps.Size(12,20);
tinyIcon.shadowSize = new google.maps.Size(22,20);
tinyIcon.iconAnchor = new google.maps.Point(6,20);
tinyIcon.infoWindowAnchor = new google.maps.Point(5,1);
// Show map points
var m1 = new google.maps.Marker(new google.maps.LatLng(35.2602340, -93.7939480), {icon:tinyIcon,bouncy:1});
google.maps.Event.addListener(m1, "click", function()
{
m1.openInfoWindowHtml(
'1<br />test,TX'
);
});
map.addOverlay(m1);
var m2 = new google.maps.Marker(new google.maps.LatLng(35.2810510, -93.8246510), {icon:tinyIcon,bouncy:1});
google.maps.Event.addListener(m2, "click", function()
{
m2.openInfoWindowHtml(
'test<br />test,Texas'
);
});
map.addOverlay(m2);
}
google.setOnLoadCallback(initialize);
So when i go to use a trigger event
google.maps.event.trigger(markers[m3], 'click');
Nothing happens, and I cant figure out the correct trigger to make it do so...
Based on the code sample you posted there is no markers[m3] defined, wouldn't you need to use google.maps.event.trigger(m2, 'click'); ? (m3 isn't defined at all in that code sample)