I've searched all over the web and SO, but I couldn't figure this out.
Here's the problem:
I'm using the below demo from jquery-ui-map site to load a JSON file:
http://jquery-ui-map.googlecode.com/svn/trunk/demos/jquery-google-maps-json.html
It works fine to load my markers, but I need to refresh its content every 30 seconds and grab new markers.
At first I thought I would just call the function again, but that left the markers there. After some research I found out I needed to clear the markers (not so easy on V3, but I was able to to do) but the issue is that I can't get the markers to show again.
If I use the destroy function, then I'm able to reload new markers and remove the old ones, but that causes the map to blink. When I try to clear markers then no new markers are shown.
Any help is greatly appreciated.
Below is my code:
<script type="text/javascript">
function mapTest() {
$('#map_canvas').gmap('destroy');
//clearMap();
demo.add(function() {
$('#map_canvas').gmap({'disableDefaultUI':true, 'callback': function() {
var self = this;
$.getJSON( 'json/demo.json?'+ new Date().getTime(), function(data) {
$.each( data.markers, function(i, marker) {
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds':true } ).click(function() {
self.openInfoWindow({ 'content': marker.content }, this);
});
});
});
}});
}).load();
}
function clearMap(){
$('#map_canvas').gmap('clear', 'markers');
}
mapTest();
setInterval(mapTest, 30000 );
</script>
Cheers.
Your map initialization function is inside the mapTest() function - which you call over an over again every 30 seconds with setInterval.
That is wrong, because you are essentially reloading the map( you destroy it and then recreate it again every 30 seconds ), and that is why it blinks.
Place the map initialization outside the mapTest(), but clear and retrieve new markers from within the mapTest()
Update:
var mapOptions = {
disableDefaultUI: true
// add more options if you wish.
};
function mapTest() {
$('#map_canvas').gmap('clear', 'markers'); // clear old markers
$.getJSON( 'json/demo.json?'+ new Date().getTime(), function(data) {
$.each( data.markers, function(i, marker) {
var self = this;
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds':true } ).click(function() {
self.openInfoWindow({ 'content': marker.content }, this);
});
});
});
}
$(function(){
$('#map_canvas').gmap(mapOptions, function(){
$.getJSON( 'json/demo.json?'+ new Date().getTime(), function(data) {
$.each( data.markers, function(i, marker) {
var self = this;
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds':true } ).click(function() {
self.openInfoWindow({ 'content': marker.content }, this);
});
});
});
});
setInterval(mapTest, 30000 );
});
I found a Solution to update markers without reloading the map. Try this code...
$(document).ready(function() {
var $map = $('#map_canvas');
App.drawMap($map);
setInterval(function() {
$('#map_canvas').gmap('clear', 'markers');
App.drawMap($map);
},10000);
});
var App = {
drawMap: function($divMap) {
Http.doAjaxGetJson('../../js/testjson.json', function(data) {
for (var k in data.gpsData) {
$divMap.gmap({ 'center': new google.maps.LatLng(data.gpsData[k].latitude,data.gpsData[k].longitude),'zoom':15, 'callback': function() {}});
$divMap.gmap('addMarker', {
'title':data.obj.name,
'position': new google.maps.LatLng(data.gpsData[k].latitude, data.gpsData[k].longitude),
'bounds': false,
}).click(function() {
var $_obj = $(this);
});
}
});
}
};
By this code markers will update in every 10 seconds..
Related
Hi i'm trying to show a map in my form inside a jquery dialogue,
my jquery dialogue return a partial view where i put this code inside #section scripts and i called also the maps api
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
// Where all the fun happens
function Initialize() {
// Google has tweaked their interface somewhat - this tells the api to use that new UI
google.maps.visualRefresh = true;
var Liverpool = new google.maps.LatLng(53.408841, -2.981397);
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 14,
center: Liverpool,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
// This makes the div with id "map_canvas" a google map
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// This shows adding a simple pin "marker" - this happens to be the Tate Gallery in Liverpool!
var myLatlng = new google.maps.LatLng(53.40091, -2.994464);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Tate Gallery'
});
// You can make markers different colors... google it up!
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
// a sample list of JSON encoded data of places to visit in Liverpool, UK
// you can either make up a JSON list server side, or call it from a controller using JSONResult
var data = [
{ "Id": 1, "PlaceName": "Liverpool Museum", "OpeningHours": "9-5, M-F", "GeoLong": "53.410146", "GeoLat": "-2.979919" },
{ "Id": 2, "PlaceName": "Merseyside Maritime Museum ", "OpeningHours": "9-1,2-5, M-F", "GeoLong": "53.401217", "GeoLat": "-2.993052" },
{ "Id": 3, "PlaceName": "Walker Art Gallery", "OpeningHours": "9-7, M-F", "GeoLong": "53.409839", "GeoLat": "-2.979447" },
{ "Id": 4, "PlaceName": "National Conservation Centre", "OpeningHours": "10-6, M-F", "GeoLong": "53.407511", "GeoLat": "-2.984683" }
];
// Using the JQuery "each" selector to iterate through the JSON list and drop marker pins
$.each(data, function (i, item) {
var marker = new google.maps.Marker({
'position': new google.maps.LatLng(item.GeoLong, item.GeoLat),
'map': map,
'title': item.PlaceName
});
// Make the marker-pin blue!
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
// put in some information about each json object - in this case, the opening hours.
var infowindow = new google.maps.InfoWindow({
content: "<div class='infoDiv'><h2>" + item.PlaceName + "</h2>" + "<div><h4>Opening hours: " + item.OpeningHours + "</h4></div></div>"
});
// finally hook up an "OnClick" listener to the map so it pops up out info-window when the marker-pin is clicked!
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
})
}
i'm calling the map inside a div :
<div id="map_canvas" style="height: 240px; border: 1px solid gray"> map here</div>
but the problem that my map is not showing in the dialogue, even though it works well in normal page
any help plz !?
I've solved this issue with the following code:
this code is on the main view, the #next is a trigger of the form to submit, and the #dialog is inside the #form.
$(function () {
datepair();
$('#dialog').dialog({
autoOpen: false,
modal: true,
height: 720,
width: 700,
resizable: false,
title: 'Verify Location',
show: "fade",
hide: "fade",
open: function (event, ui) {
var form = $('#form');
$.ajax({
url: form.attr('actoin'),
type: form.attr('method'),
data: form.serialize(),
context: this,
success: function (result) {
$(this).html(result);
}
});
}
});
$('#next').click(function (e) {
$('#dialog').dialog('open');
return false;
});
});
this code is on the partialView
$(function () {
window.$required = $('<div></div>').dialog({
autoOpen: false,
resizable: false,
modal: true,
title: 'Verity Location Error',
buttons: {
"Ok": function () {
$(this).dialog('close');
callback();
}
}
});
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (json) {
Initialize();
}
});
return false;
});
function callback() {
$('#dialog').dialog('close');
}
function Initialize() {
//init the map
}
and this is the controller
public ActionResult PartialViewMapController()
{
return PartialView();
}
Hope it not to late for you :)
I use jquery gmap3.
Is it possible to disable running event-listeners temporarily when I show an infowindow and enable them when I click the close-button on my infowindow?
Edit:
Here is the function that will be called when the "click"-event is fired (for big infowindow) or mouseover (then the variable "shortwindow" will be "s").
function infoWindow_open(thismap, marker, id, language, shortwindow) {
// Get InfoWindow with AJAX-Request
$.ajax({
type: "POST",
url: "getInformation_ajax.php",
data: "id="+encodeURIComponent(id)+"&language="+encodeURIComponent(language),
success: function(data) {
var json = $.parseJSON(data);
if(json.infownd === null || json.infowndshort === null) {
return;
}
var map = thismap.gmap3("get"),
infowindow = thismap.gmap3({get:{name:"infowindow"}});
if(shortwindow == "s") { // Short infowindow on mouseover
content_ = "<h class=name_gmap3'>"+json.infowndshort+"</h>";
$('#test1').gmap3({
map:{
events:{
zoom: 2,
minZoom: 1, // If 0: BUG!?
mapTypeId: google.maps.MapTypeId.SATELLITE,
//disableDefaultUI: true,
//panControl: true,
//zoomControl: true,
//scaleControl: true
}}});
if(infowindow) {
infowindow.open(map, marker);
//infowindow.setOptions({alignBottom: true});
infowindow.setContent(content_);
}
else {
thismap.gmap3({
infowindow: { anchor:marker, options:{content: content_} }
});
}
}
else {
if(infowindow) {
infowindow.setOptions({maxWidth:350/*, pixelOffet: new google.maps.Size(50,-50)*/});
infowindow.setContent(json.infownd);
infowindow.open(map, marker);
} else {
thismap.gmap3({
infowindow: { anchor:marker, options:{content: json.infownd/*, pixelOffet: new google.maps.Size(50,-50)*/} }
});
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// Do nothing!
//$("#erroutp#").html(textStatus);
}
});
}
Inside the mouseover-callback(that opens the small window) check the map-property of the big InfoWindow.
When it's not null the big infowindow is open, leave the mouseover-callback without opening the small infoWindow.
Modified code with some improvements(removed duplicate parts, caching of content):
function infoWindow_open(thismap, marker, id, language, shortwindow) {
//initialize infowindow on first run
var infowindow = thismap.gmap3({get:{name:"infowindow"}})
||
thismap.gmap3({infowindow: {options:{'shortwindow':'s'} }})
.gmap3({get:{name:"infowindow"}}),
key = (shortwindow==='s')
?'s':'l',
//options for the InfoWindow
iwOpts = {
//small
s:{maxWidth:350},
//large
l:{}
},
//options for the map
mapOpts = {
//small
s:{},
//large
l:{}
},
//function that sets the content
//and opens the window
setOpts = function(marker){
//set infowindow-options
infowindow.setOptions($.extend({},
iwOpts[key],
{
content:marker.get('content')[key],
//property to determine if it's
//a small or large window
shortwindow:shortwindow
}
)
);
//open the infowindow
infowindow.open(marker.getMap(),marker);
//set map-options
marker.getMap().setOptions(mapOpts[key]);
}
//leave the function onmouseover
//when a big infowindow is open
if(shortwindow==='s'
&& infowindow.get('shortwindow')!=='s'
&& infowindow.getMap()){
return;
}
if(marker.get('content')){
console.log('cached');
setOpts(marker);
return;
}
// Get InfoWindow-content with AJAX-Request
$.ajax({
type: "POST",
url: "getInformation_ajax.php",
data: "id="+encodeURIComponent(id)+"&language="+encodeURIComponent(language),
success: function(data) {
var json = $.parseJSON(data);
if(json.infownd === null || json.infowndshort === null) {
return;
}
//cache the content as marker-property
marker.set('content',
{s:"<h3 class=name_gmap3'>"+json.infowndshort+"</h3>",
l: json.infownd});
//open infoWindow
setOpts(marker);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// Do nothing!
//$("#erroutp#").html(textStatus);
}
});
}
I can't get a custom icon to display using this code below. It just defaults to the default Google maps marker.
Any ideas where I'm going wrong?
$(function() {
$('#map_canvas').gmap({
'center':new google.maps.LatLng(54.5,-4.0),
'zoom':6,
'streetViewControl': false,
'callback':
function() {
setInterval( function() {
$.getJSON( 'URL/data_sets/json/sfuk47.php?'+ new Date().getTime(), 'category=activity', function(data) {
$.each( data.markers, function(i, m) {
$('#map_canvas').gmap(
'addMarker',{
'position': new google.maps.LatLng(m.lat, m.lng) });
});
});
}, 5000);
}
});
});
setInterval( function() {
$.ajax({
url:'URL/data_sets/json/sfuk47.php',
success: function(data) {
if (data == "refresh"){
window.location.reload();
}
}
});
}, 600000);
The JSON
{"markers":[
{"lat":59.889,"lng":1.249,"icon":"URL/icons/gl_icons/Red.png"},{"lat":59.892,"lng":1.235,"icon":"URL/icons/gl_icons/Red.png"},{"lat":56.778,"lng":-5.702,"icon":"URL/icons/gl_icons/Red.png"},{"lat":49.534,"lng":-1.814,"icon":"URL/icons/gl_icons/Red.png"},{"lat":56.608,"lng":-8.324,"icon":"URL/icons/gl_icons/Red.png"},{"lat":49.286,"lng":-2.183,"icon":"URL/icons/gl_icons/Red.png"},{"lat":49.289,"lng":-2.192,"icon":"URL/icons/gl_icons/Red.png"},{"lat":59.051,"lng":-7.525,"icon":"URL/icons/gl_icons/Red.png"},{"lat":58.965,"lng":-7.439,"icon":"URL/icons/gl_icons/Red.png"},{"lat":57.531,"lng":-6.895,"icon":"URL/icons/gl_icons/Red.png"},
{"lat":56.895,"lng":-6.372,"icon":"URL/icons/gl_icons/Red.png"}]}
Many thanks,
At first glance you're not setting the icon in the markers call. Try doing:
'addMarker',{
'position': new google.maps.LatLng(m.lat, m.lng),
'icon': m.icon });
But be aware you appear to be using API v2 which is deprecated.
Some relevant examples for API V3.
hello i am working on the phonegap apps which can display the location markers on google map.
It is supposed to have a detail box pop up when i click on the marker, but it does not function.
can anyone help me to correct the code?
many thanks
var mobileDemo = { 'center': '57.7973333,12.0502107', 'zoom': 8 };
////////////////////////////////////////////////////////////
$('#basic_map').live('pageinit', function() {
demo.add('basic_map', function() {
$('#map_canvas').gmap({'center': mobileDemo.center, 'zoom': mobileDemo.zoom, 'disableDefaultUI':true,
'callback': function() {
var self = this;
self.addMarker({'position': this.get('map').getCenter() }).click(function() {
self.openInfoWindow({ 'content': 'Hello World!' }, this);
});
}});
$('#map_canvas').gmap('addMarker', { position: new google.maps.LatLng(57.9973333,12.0502107)})
.click(function() {
var self = this;
self.openInfoWindow({ 'content': 'Hello Worl23!' }, this);
} )
$('#map_canvas').gmap('addMarker', { position: new google.maps.LatLng(57.373333,12.0502107)})
.click(function() {
var self = this;
self.openInfoWindow({ 'content': 'Hello Worl234!' }, this);
} )
}).load('basic_map');
});
$('#basic_map').live('pageshow', function() {
demo.add('basic_map', function() { $('#map_canvas').gmap('refresh'); }).load('basic_map');
});
</script>
There is a easier way to use Google Maps api,https://github.com/HPNeo/gmaps. And what you need almost like this,http://hpneo.github.com/gmaps/examples/markers.html, you click the marker and the detail info shows
$('#map_canvas').gmap().bind('init', function(ev, map) {
if (myPosition) {
$('#map_canvas').gmap({ 'center' : myPosition });
$('#map_canvas').gmap('addMarker', { 'position': myPosition, 'bounds': true, 'icon' : '../../css/images/current_location.png'}).click( function () {
$('#map_canvas').gmap('openInfoWindow', { 'content': 'You are here!' }, this);
});
$('#map_canvas').gmap('option', 'zoom', 20);
} else {
$('#map_canvas').gmap('option', 'zoom', 8);
}
$.each(markers, function(i, marker) {
$('#map_canvas').gmap('addMarker', {
'position': new google.maps.LatLng(marker.lat, marker.lng),
'bounds': true
}).click(function() {
$('#map_canvas').gmap('openInfoWindow', { 'content': marker.name }, this);
});
});
});
I want to center and zoom to specific position. The result of this piece of code: http://postimage.org
Add the latLng of each marker to a LatLngBounds object, then use fitBounds()
Here is an example.
All in all I reached my purpose, but fitBounds() function did some mess to my expectation. My task was: create lot of makers and place them in the map. If I was use fitBounds() function my map zooms out to fit all my markers. Now how does look like my map: http://postimage.org