I'm trying to update a marker in real time on a Google Map. I need a marker for the starting location and then as the location changes (the user moves) a polyline will be drawn and a marker will show the current location. So, for each user there will be two markers; one showing the start location and one that keeps updating and showing the current location.
I can get the lines drawn and the start marker to work, but with this code each time the location changes, a new marker is placed instead of the old one being updated. I'm trying to use setPosition(); but it doesn't seem to work. Any thoughts?
function initialize() {
var myLatlng = new google.maps.LatLng(39, -86);
var myOptions = {
zoom: 6,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var loc = {};
var mark = {};
var markers = {};
$(function () {
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: 'api.php', //the script to call to get data
//data: "",
dataType: 'json', //data format
success: function(data){ //on recieve of reply
var user_id = data[0];
var lati = data[1]; //get id
var longi = data[2]; //get name
var myLatlngt = new google.maps.LatLng(lati, longi);
if (typeof loc[user_id] === 'undefined') {
loc[user_id] = [];
}
//if (typeof markers[user_id] === 'undefined') {
//markers[user_id] = [];
//}
if (typeof mark[user_id] === 'undefined') {
mark[user_id] = myLatlngt;
}
loc[user_id].push(myLatlngt);
//markers[user_id].push(myLatlngt);
var marker1;
var x;
for (x in loc) {
var polyline = new google.maps.Polyline({
map: map,
path: loc[x],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
///location variables
var start_loc = loc[user_id];
var start_marker = start_loc[0]; //start location of given user
var current_loc = start_loc[start_loc.length -1]; //last known location of given user
//set the start marker
var marker = new google.maps.Marker({
position: start_marker,
title: user_id
});
marker.setMap(map);
//update the current location marker
if (marker1 != null) {
marker1.setPosition(current_loc);
}
else {
marker1 = new google.maps.Marker({
position: current_loc,
map: map
});
}
}
//console.log('location :::', x);
console.log('Marker: ', mark);
}
});
}, 1000);
});
});
}
Try declaring your marker1 variable (var marker1;) outside the function to make it global (scope). Right after var markers = {}; should do it. Let me know if this does not work, and I will look in to it deeper.
Related
Hi i'm trying to get markers latlon from ajax, i m getting ajax data every second and also able to create marker within radius , now i'm facing problem with updating marker positions as in current new marker created and old one also showing. Pls help to update markers which i am getting from ajax and remove extra.
var map = null;
var geocoder = null;
var markers = {};
var infoWindow = null;
var minZoomLevel = 16;
jQuery('#search').click(function() {
var address = jQuery('#address').val() || 'India';
if (map === null)
initializeMap();
searchAddress(address);
});
function initializeMap() {
var mapOptions = {
zoom: minZoomLevel,
draggable: true,
disableDefaultUI: true,
scrollwheel: true,
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
});
}
google.maps.event.addListener(map, "idle", function(event) {
searchStoresBounds();
});
geocoder = new google.maps.Geocoder();
infoWindow = new google.maps.InfoWindow();
}
function searchAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var latlng = results[0].geometry.location;
map.setCenter(latlng);
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
searchStoresBounds();
} else {
alert('Geocode was failed: ' + status);
}
});
}
setInterval(function searchStoresBounds() {
var bounds = map.getCenter().toUrlValue();
var url = './store.php';
var parameter = { bounds: bounds };
jQuery.ajax({
url: url,
data: parameter,
dataType: 'json',
success: showStores
});
}, 1000);
function showStores(data, status, xhr) {
if (data['status'] != 'OK')
return;
var id;
// add markers for new stores
for (id in data['data']) {
if (markers[id] === undefined)
createMarker(id, data['data'][id]);
}
var b = map.getBounds();
// remove markers out of the bounds
for (id in markers) {
if (! b.contains(markers[id].getPosition())) {
markers[id].setMap(null);
delete markers[id];
}else{createMarker(id, data['data'][id]);}
}
}
function createMarker(id, store) {
var latlng = new google.maps.LatLng(
parseFloat(store['lat']),
parseFloat(store['lng'])
);
var html = "<b>" + store['address'] + "</b>";
var x = store['distance'];
var y = 1000;
var z = x * y;
var m = 85;
var t = z / m;
document.getElementById("demo").innerHTML = Math.ceil(t);
var headm = store['bearing'];
var car = "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-
2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z
M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z
M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z
M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z";
var icon = {
path: car,
scale: .7,
strokeColor: 'White',
strokeWeight: .4,
fillOpacity: 1,
fillColor: '#333333',
offset: '5%',
rotation: parseInt(headm),
// rotation: parseInt(heading[i]),
anchor: new google.maps.Point(10, 25) // orig 10,50 back of car, 10,0 front of car, 10,25 center of car
};
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers[id] = marker;
}
You are facing the issue due to this part
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
Everytime you get data from ajax it creates a new marker.
Add the following declaration at the top of your js page
var marker;
and change the marker creation to the following
if(marker)
{
marker.setMap(null);
}
marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
Before you create a new marker the previous one is removed from the map. The if(marker) part is needed to check if a marker instance has been created because the first time that you run there will be no marker and you will get an error while trying to remove the marker.
Edit 1 :
As you have multiple markers you will need to store an array of markers and remove them before adding new markers on map
At the top of the page you will need to declare
var markerArray = new Array();
Just before you add the markers you will need to clear the previous markers
for(var i = 0; i<markerArray.length; i++)
{
markerArray[i].setMap(null);
}
markerArray = new Array()
After that will be your current code
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
markerArray.push(marker);
You will need to add the marker to the markerArray so that it can be cleared the next time your code executes.
I am trying to plot on a google map a set of fixed markers and a marker for the user position. For these two sets of markers I would like to use a different image for the marker, however something weird is happening: when loading the page, the "fixed" markers get plotted properly but then immediately one disappears (the last one in the array) and then the user position shows up. In addition, the first fixed location gets the user location marker image, and the user positioning marker gets the image of the fixed markers. Ideally, the locations in the array will be plotted entirely (all 4) and with red_dot.png image on the marker, and the user positioning with the bluedot_retina.png on the marker.
It's really strange and I am struggling figuring out what is the root cause. Appreciate any help with this issue. thanks!
<script>
var locations = [
['location a', 37.60756088, -122.42793323],
['location b', 37.759736, -122.426957],
['location c', 37.752950, -122.438458],
['location d', 37.763128, -122.457942]
];
var map;
var i;
var marker;
var google_lat = 37.757996;
var google_long = -122.404479;
var myLatlng = new google.maps.LatLng(google_lat, google_long);
//google.maps.visualRefresh = true;
function initialize() {
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var image_dot = new google.maps.MarkerImage(
'images/red_dot.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 8, 8 ) // scaled size (required for Retina display icon)
);
marker = new google.maps.Marker({
flat: true,
position: myLatlng,
icon: image,
optimized: false,
map: map,
visible: true,
title: 'I might be here'
});
setMarkers(map, locations);
} //initialize();
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng1 = new google.maps.LatLng(beach[1], beach[2]);
marker = new google.maps.Marker({
position: myLatLng1,
icon: image_dot,
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script type="text/javascript">
var Tdata;
var image = new google.maps.MarkerImage(
'images/bluedot_retina.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 17, 17 ) // scaled size (required for Retina display icon)
);
var userMarker = new google.maps.Marker({icon: image});
//var userMarker = new google.maps.Marker({icon: 'images/bluedot_retina.png'});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
// console.log(data.lat);
console.log(Tdata.lat);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
console.log(google_lat, google_long);
// $('#data').html('google_lat, google_long');
myLatlng = new google.maps.LatLng(google_lat, google_long);
//marker.setPosition(myLatlng);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
//map.setCenter(myLatlng);
});
}, 1000);
}
</script>
marker is a global variable. You are using it for both all of your locations and your user's position marker. Don't do that, assign unique (or local) names to the two classes of markers.
var Tdata;
var userMarker = new google.maps.Marker({icon: URL/to/custom/icon/for/user});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
// console.log(data.lat);
console.log(Tdata.lat);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
console.log(google_lat, google_long);
// $('#data').html('google_lat, google_long');
myLatlng = new google.maps.LatLng(google_lat, google_long);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
map.setCenter(myLatlng);
});
}, 1000);
}
I am building a Google Maps based web app on which I plot a moving dot of the user location. I am fetching continuously the user location from a server and would like to use the current user location when loading the map to center the window around it, meaning, when the user loads the site, the map will be centered around the first lat/long fetched from the server but enable the user to pan the map afterwards without re-centering it around where the user is. I was able to keep the map centered constantly around the user location but can't figure out how to use the first fetched location to center the map during initialization. My code is below, any help would be greatly appreciated. Thanks!
<script>
var locations = [
['location a', 37.771678, -122.469357],
['location b', 37.768557, -122.438458],
['location c', 37.755121, -122.438973],
['location d', 37.786127, -122.433223]
];
var map;
var i;
var marker;
var google_lat = 37.722066;
var google_long = -122.478541;
var myLatlng = new google.maps.LatLng(google_lat, google_long);
var image_dot = new google.maps.MarkerImage(
'images/red_dot.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 8, 8 ) // scaled size (required for Retina display icon)
);
function initialize() {
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
setMarkers(map, locations);
} //initialize();
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng1 = new google.maps.LatLng(beach[1], beach[2]);
marker = new google.maps.Marker({
position: myLatLng1,
icon: image_dot,
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script type="text/javascript">
var Tdata;
var image = new google.maps.MarkerImage(
'images/bluedot_retina.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 17, 17 ) // scaled size (required for Retina display icon)
);
var userMarker = new google.maps.Marker({icon: image});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
myLatlng = new google.maps.LatLng(google_lat, google_long);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
//map.setCenter(myLatlng); --> this is not what I want since it will always keep the map centerd around the user
});
}, 1000);
}
</script>
Only set the map center the first time. One way of detecting the first time would be to create the "userMarker" the first time the data is loaded.
var userMarker;
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
myLatlng = new google.maps.LatLng(google_lat, google_long);
if (!userMarker || !userMarker.setPosition) {
// create the marker
userMarker = new google.maps.Marker({
icon: image,
position: myLatlng,
map:map
});
// center the map the first time, when the marker is created
map.setCenter(myLatlng);
} else { // marker aleady exists
userMarker.setPosition(myLatlng);
}
});
}, 1000);
}
proof of concept fiddle
I am trying to add google maps to my web page, the web page has div with id of radar with width specified. I get coordinates from a second page using jquery ajax method, and plot them on the map using Marker. But only the last marker is displayed nothing else is displayed.
var global = new Array();
$(document).ready(function () {
console.log("ready!");
if ($("#StartingDate").val() != "") {
var start = $("#StartingDate").val();
var end = $("#EndingDate").val();
var id = $("#UserId").val();
$.ajax({
url: "GetData.aspx?StartingDate=" + start + "&EndingDate=" + end + "&UserId=" + id, async: false, success: function (result) {
var resp = result.split(",");
for (x = 0; x < resp.length - 1; x++) {
var cor = resp[x].split(";");
var lat = cor[0];
var lon = cor[1];
var date = cor[2]
var temp = [lat, lon, date];
global.push(temp);
}
}
});
}
});
$(document).ajaxComplete(function () {
var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("radar"), mapOptions);
for (var i = 0; i < global.length; i++) {
console.log(global[i]);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(global[i][0]),parseFloat(global[i][1])),
title: global[i][2]
});
marker.setMap(map);
}
});
After the ajax call succeeds my variable named global is filled like this:
global = [
[
0: "33.622835",
1: "73.062932",
2: "16/06/2015 1:17:24 AM"
],....
];
Edit: Turns out you have to set the .ajaxComplete handler before you make the ajax request since you have set async to false.
Here is a working example.
I would suggest saving the markers in an array if you intend to use the markers later on(i.e.: move them, or remove them).
Only the last marker is displayed because you override it every time. What you need to do is save the marker in an array.
What i would do is create a function addMarker which creates a marker with the given coordinates and a title and returns it.
This would look something like this:
function addMarker(title, x, y, map){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(x,y),
map: map,
title: title
});
return marker;
}
This function should be called where you currently are setting the marker in the for-loop:
for (var i = 0; i < global.length; i++) {
console.log(global[i]);
markerArray[i] = addMarker(global[i][2], global[i][0], global[i][1], map);
}
markerArray needs to be a global array like global.
Hello
I'm looping over a JSON object and creating a new map marker for each item. After the marker is created, I push it to an array (var markers) for future manipulation. Problem is, when I try to access the array items (eg: console.log(markers[3])), I am given an "undefined" value.
Relevant code below:
var map;
var markers = [];
var activeFilters = [];
function initializeMap() {
var myLatlng = new google.maps.LatLng( 51.506873, -0.125141);
var myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById("location_map"), myOptions);
$.getJSON('../js/hotspots.json', function(data) {
var hotspots = data.scenes[0].hotspots;
$.each(hotspots, function(i) {
var lat = hotspots[i].latitude;
var lon = hotspots[i].longitude;
var point = new google.maps.LatLng(lat,lon);
var cat = hotspots[i].hotspottype;
var weburl = hotspots[i].weburl;
var marker = addMarker(point,cat,weburl);
});
});
}
function addMarker(point, cat, weburl) {
var markerUrl = weburl;
var marker = new google.maps.Marker({
position: point,
map: map
});
marker.category = cat;
markers.push(marker);
};
initializeMap();
console.log(markers[3]);
Any help would be greatly appreciated.
get json runs asynchronously. try this:
$.getJSON('../js/hotspots.json', function(data) {
var hotspots = data.scenes[0].hotspots;
$.each(hotspots, function(i) {
var lat = hotspots[i].latitude;
var lon = hotspots[i].longitude;
var point = new google.maps.LatLng(lat,lon);
var cat = hotspots[i].hotspottype;
var weburl = hotspots[i].weburl;
var marker = addMarker(point,cat,weburl);
});
console.log(markers);
});
Try to
console.log(markers[0]);
because looking at your code, there is just one element in markers array.
If you will put into that array 4 elements, then using markers[3] you will access fourth element.
try:
initializeMap();
setTimeout(function(){
console.log(markers[3]);
}, 10000);