infowindow is not updating with marker google maps - javascript

I am developing a web page for viewing vehicle locations using gps data.
I have make the back end working fine with the help of Mr. Aruna a genius in stack Overflow. Now I need a help for updating my google map infowindow. marker is updating its location no issue with that. while clicking it is not updating is current speed and another info according to that.
Below is the code in
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
getMarkers();
function getMarkers() {
var infowindow = null;
$.get('/markers', {}, function (res, resp) {
console.dir(res);
for (var i = 0, len = res.length; i < len; i++) {
var content = res[i].name + " S1: " + res[i].speed * 1.6 + '<br />' + "D: " + res[i].lastupdate
infowindow = new google.maps.InfoWindow({
content: "A"
});
//Do we have this marker already?
if (markerStore.hasOwnProperty(res[i].id)) {
console.log('just move it...');
markerStore[res[i].id].setPosition(new google.maps.LatLng(res[i].position.lat, res[i].position.long));
//markerStore[res[i].id].setMap(map);
// Not sure below block and its not updating
google.maps.event.addListener(markerStore[res[i].id], 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, markerStore[res[i].id]);
};
})(markerStore[res[i].id], content, infowindow));
} else {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(res[i].position.lat, res[i].position.long),
title: res[i].name,
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, marker);
};
})(marker, content, infowindow));
//var marker = new google.maps.Marker({
// position: new google.maps.LatLng(res[i].position.lat, res[i].position.long),
// title: res[i].name,
// map: map
//});
//google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
// return function () {
// infowindow.setContent(content);
// infowindow.open(map, marker);
// };
//})(marker, content, infowindow));
markerStore[res[i].id] = marker;
console.log(marker.getTitle());
}
}
window.setTimeout(getMarkers, INTERVAL);
}, "json");
}
Please help me ...

Your click event listener is called asynchronously, long after your for loop has completed. So the value of i is not what you expect.
This is easy to fix (assuming there are not other problems as well).
Take all of the code inside the for loop body and make it a function. I'll call the function addMarker( item ), but of course you can use any name you want.
Everywhere you have res[i] in that function, change it to item. Then shorten the for loop so it contains only a single line: addMarker( res[i] );.
So now your code looks like this:
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
getMarkers();
function getMarkers() {
var infowindow = null;
$.get('/markers', {}, function (res, resp) {
console.dir(res);
for (var i = 0, len = res.length; i < len; i++) {
addMarker( res[i] );
}
function addMarker( item ) {
var content = item.name + " S1: " + item.speed * 1.6 + '<br />' + "D: " + item.lastupdate
infowindow = new google.maps.InfoWindow({
content: "A"
});
//Do we have this marker already?
if (markerStore.hasOwnProperty(item.id)) {
console.log('just move it...');
markerStore[item.id].setPosition(new google.maps.LatLng(item.position.lat, item.position.long));
//markerStore[item.id].setMap(map);
// Not sure below block and its not updating
google.maps.event.addListener(markerStore[item.id], 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, markerStore[item.id]);
};
})(markerStore[item.id], content, infowindow));
} else {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.position.lat, item.position.long),
title: item.name,
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, marker);
};
})(marker, content, infowindow));
//var marker = new google.maps.Marker({
// position: new google.maps.LatLng(item.position.lat, item.position.long),
// title: item.name,
// map: map
//});
//google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
// return function () {
// infowindow.setContent(content);
// infowindow.open(map, marker);
// };
//})(marker, content, infowindow));
markerStore[item.id] = marker;
console.log(marker.getTitle());
}
}
window.setTimeout(getMarkers, INTERVAL);
}, "json");
}
I didn't check for any other errors in your code, but this will fix the specific problem you are asking about.
To learn more about this, read up on JavaScript closures.

Related

Remove markers from map before adding new markers

I have a map where initially the markers load coming from the database, Then i have a time based Ajax request which gets the records again after every 1 minute.
Following is the code where i am using setMapOnAll(null) as from the Google maps Documentation, But its not working.
success: function(data){
var positions = [];
$.each(data.riders, function(index, value) {
positions.push({
lat: value.rider_location.lat,
lng: value.rider_location.lng,
content: value.name,
id : value.id
});
});
map.setCenter({
lat: parseInt(positions[0].lat),
lng: parseInt(positions[0].lng)
});
var infowindow = new google.maps.InfoWindow();
var marker,
i;
setMapOnAll(null); //Remove the existing markers
while(positions.length){
positions.pop().setMap(null);
}
for (i = 0; i < positions.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(positions[i].lat,positions[i].lng),
map: map,
id : positions[i].id,
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
}
}) (marker, i));
}
}
How can i remove the existing markers before adding new ones.
there is method marker.setMap(null) as google docs https://developers.google.com/maps/documentation/javascript/markers
you need create array of markers then remove all from map in loop by call method marker.setMap(null)
var markers = [];
for (i = 0; i < positions.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(positions[i].lat,positions[i].lng),
map: map,
id : positions[i].id,
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
}
}) (marker, i));
}
You should add this function to your code and call it where you add new markers then add new markers. This will delete the previous markers.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}

how to use ng click and pass the id in google map pop window using angularjs?

i have two stores in database and am trying to get stores in google map marker is pointing that two stores.i have ng-click in that info window to pass id here ng-click is not working is there any idea to pass id through ng-click
.controller('MapCtrl', [
'$scope', '$http', '$location', '$window',
function ($scope, $http, $location, $window) {
$http.get('****').success(function (data, dealers, response) {
function initialize() {
var serverData = data;
$scope.locations = [];
for (var i = 0; i < serverData.length; i++) {
var modal = [
data[i].Store_Name, data[i].S_Location.Latitude, data[i].S_Location.Longitude, i, 'images/arrow.svg', data[i].S_Address];
$scope.locations.push(modal);
}
console.log($scope.locations);
//---------------------------------------------------------
//console i am getting like this
var locations = [
['nokia store', '12.971599', '77.594563', '1', 'images/arrow.svg.svg', '55a78953815356700bee698f'],
['samsung store', '12.9065534', '77.5774802', '2', 'images/arrow.svg.svg', '55a786d1815356700bee6982'], ];
//----------------------------------------------------------
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(12.9667, 77.5667),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < $scope.locations.length; i++) {
//console.log($scope.locations[i][1]);
marker = new google.maps.Marker({
position: new google.maps.LatLng($scope.locations[i][1], $scope.locations[i][2]),
map: map,
icon: $scope.locations[i][4],
animation: google.maps.Animation.DROP,
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('<div class="marker-box"><div class="marker-title">' + $scope.locations[i][0] + '</div><input type="button" value="Book Now" name="Book Now" ng-click="getid(' + $scope.locations[i][5] + ') "/></div>');
infowindow.open(map, marker);
}
})(marker, i));
}
$scope.map = map;
}
$scope.getid(id) {
console.log(id);
}
});
since 3 days i'm trying i can't able to solve.help me out
So in your code:
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('<div class="marker-box"><div class="marker-title">' + $scope.locations[i][0] + '</div><input type="button" value="Book Now" name="Book Now" ng-click="getid(' + $scope.locations[i][5] + ') "/></div>');
infowindow.open(map, marker);
}
})(marker, i));
your call back function does not run until marker is clicked. By the time it's clicked, the scope probably does not know what "i" is. My guess is "i" becomes $scope.locations.length+1.
One things you can try:
put the above code in a secondary function, then call it from the main thread instead of running it directly from main thred. IE:
main code:{
//your code
for (i = 0; i < $scope.locations.length; i++){
function_name(parameter 1, i);
}
function function_name= above code;
Note the above is sudo code, please implement it and try it. Hope this solves it.

JavaScript multidimensional array cannot access as array, only as string

I am trying to put multiple markers on a Google map. I have JS that builds an array and passes it to the Google function that handles markers.
Problem is, when I try to access the supposed array, I just get the first character as if it's a string.
$(document).ready(function () {
// initialize map to center on florida.
initializeGMap();
var locations = [];
#foreach (var item in Model)
{
<text>
locations.push(#Html.Raw(Json.Encode("'" + item.Name + "'," + item.Location.Latitude + "," + item.Location.Longitude + "")));
</text>
}
addMarker(locations);
});
I've tried several (read: 20+) variations of this including JSON.stringify it before sending, after sending, etc. Here's the function it gets passed too:
function addMarker(locations) {
var locations = JSON.stringify(locations);
alert(locations + '\n' + locations[0][0] + '\n' + locations[0][1]);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
alert("done");
}
When it gets to the line with 'locations[x][x]' all I ever get back in '[' which is the first character of the JSON string. It's not being treated at an array.
What am I missing?
I solved it via:
$(document).ready(function () {
// initialize map to center on florida.
initializeGMap();
// serialize model locations
var locationsToPass = #Html.Raw(Json.Encode(Model.Select(x => new { x.Name, x.Location.Latitude, x.Location.Longitude })));
addMarker(locationsToPass);
});
and in the receiving function:
function addMarker(locations) {
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].Latitude, locations[i].Longitude),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i].Name);
infowindow.open(map, marker);
}
})(marker, i));
}
}
The key to troubleshooting was using this to detect if I was passing an array or not:
variable.constructor === Array
which I got here.

JQuery:Google map loads partially

I am trying to integrate GoogleMap in hash page in my project.When I navigate from a page to mappage
googlemap loads partially.When i refresh this hash page it loads successfully.This is the code :
function markicons() {
InitializeMap();
var ltlng = [];
ltlng.push(new google.maps.LatLng(-36.847043, 174.761543));
ltlng.push(new google.maps.LatLng(-37.791174,175.297813));
ltlng.push(new google.maps.LatLng(-38.679988,176.077843));
ltlng.push(new google.maps.LatLng(-41.297257,174.759483));
map.setCenter(ltlng[0]);
for (var i = 0; i <= ltlng.length; i++) {
marker = new google.maps.Marker({
map: map,
position: ltlng[i]
});
(function (i, marker) {
google.maps.event.addListener(marker, 'click', function () {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent("Message" + i);
infowindow.open(map, marker);
});
})(i, marker);
}
}
window.onload = markicons;
How can I fix this problem?Please suggest a solution.
I got the solution.I just called markicons() inside the window.hashchange function not in the window.load.Here is the code:
$(window).on("hashchange", function () {
if(window.location.hash=="#contactUI")
{
markicons();
}
});

Different results in Google Places API and Google Maps

I'm using the Google Places JavaScript API for a desktop application. However, the search results returned by the API aren't the same as the ones I get in maps.google.com. For instance, if I search for "Antique Hostel", I get many results (almost all of them are kinda random) whereas on Google Maps I get the correct (single) result.
Is the quality of the search isn't the same in the API and the service?
Here is my code
function initialize() {
// map setup
var mapOptions = {
center: new google.maps.LatLng(52.519171, 13.406091199999992),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
$map = document.getElementById('mapCanvas'),
map = new google.maps.Map($map, mapOptions),
input = document.getElementById('searchInput'),
autocomplete = new google.maps.places.Autocomplete(input),
service = new google.maps.places.PlacesService(map),
$ajaxSearchInput = $(input),
markers = [];
autocomplete.bindTo('bounds', map);
$ajaxSearchInput.keydown(function(e) {
if (e.keyCode === 13) {
var request = {
query: $(this).val(),
radius: '500',
location: map.getCenter()
}
service.textSearch(request, searchCallBack);
}
});
searchCallBack = function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
console.log(results);
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i], bounds);
}
map.fitBounds(bounds);
}
}
createMarker = function(place, bounds) {
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
});
// event listener to show the InfoWindow.
(function(marker, place) {
google.maps.event.addListener(marker, 'click', function() {
var content = '<h3>' + place.name + '</h3> ' + place.formatted_address + '<br>',
infowindow = new google.maps.InfoWindow({
content: ''
});
if (place.rating) {
content += '<p> <b>Rating</b>: ' + place.rating + '</p>';
}
if (place.types) {
content += '<p> <b>Tags</b>: ';
for (var j = 0, tag; tag = place.types[j]; j++) {
content += tag + ', '
}
content += '</p>';
}
infowindow.content = content;
infowindow.open(map, marker);
});
})(marker, place);
markers.push(marker);
bounds.extend(place.geometry.location);
}
}
google.maps.event.addDomListener(window, 'load', initialize);

Categories