This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I want to display content into InfoWindow from controller action (return partial view). When i click Mraker it shows 'Undefined' into infowindow.
How to render partial view into google map InfoWindow?
function AjaxDisplayString() {
var addressData;
var testData;
$.ajax({
type: "GET",
url: '/Account/Tooltip',
dataType: "HTML",
contentType: 'application/json',
traditional: true,
data: addressData,
success: function (result) {
debugger;
return result
},
error: function (arg) {
alert("Error");
}
});
}
var infowindow = new google.maps.InfoWindow({
content: "<div>"+ AjaxDisplayString() + "</div>"
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
AjaxDisplayString is ajax call hence result arrives little late but you tend to open infowindow immediately. Modify the calls as below and it shall work.
var infowindow = new google.maps.InfoWindow({
content: "";
});
function AjaxDisplayString() {
var addressData;
var testData;
$.ajax({
type: "GET",
url: '/Account/Tooltip',
dataType: "HTML",
contentType: 'application/json',
traditional: true,
data: addressData,
success: function (result) {
debugger;
infowindow.setContent("<div>"+ result + "</div>");
infowindow.open(map, marker);
},
error: function (arg) {
alert("Error");
}
});
}
google.maps.event.addListener(marker, 'click', function () {
AjaxDisplayString(map, marker)
});
Related
I am trying to get multiple JSON data with deferred object. I have JSON files for individual days. In each individual day, I have data for points, lines and polygons. I have jQueryUI Sliders to visualise for individual days. For example, if the slider has value of 1, only the day1 data (points, lines and polygons) need to be visualised, and for day2, all points, lines and polygons relating to day2 only should be visualised and so on.
I don't know what is problem with my code but it is not serving the required data. Latest data/merged data is shown.
Help me out here.
$(document).ready(function () {
var map = L.map("map", {
center: [27.6419412, 85.1224152],
zoom: 13,
doubleClickZoom: true
});
L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap'
}).addTo(map);
L.control.scale().addTo(map);
var markerCluster = L.markerClusterGroup({
showCoverageOnHover: false
});
function TableContent(jsonData) {
var content = $('<div></div>').addClass('table-content');
for (row in jsonData) {
var tableRow = $('<div></div>').addClass('table-row').append(function () {
var key = row;
if (!(key === "#uid" || key === "#changeset" || key === "#version" || key === "#timestamp" || key === "#id")) {
return jsonData[row] ? $("<div></div>").text(key).append($("<div></div>").text(jsonData[row])) : "";
}
});
tableRow.prependTo(content).addClass(row);
}
return $(content)[0];
}
function Table(json) {
return $('<div></div>').append($('<div class="title"></div>').text(json.type)).addClass('table-container').append(new TableContent(json.data));
}
var pointBuild = L.geoJson(null, {
pointToLayer: function (feature, latlng) {
var deferred = $.Deferred();
marker = L.marker(latlng, {
icon: L.icon({
iconUrl: 'img/marker.png',
iconSize: [30, 30],
iconAnchor: [15, 15]
}),
riseOnHover: true,
title: "This is a Point feature. Click to have a look at some of its attributes"
});
markerCluster.addLayer(marker);
deferred.resolve();
map.fire('cluster-hover');
return marker;
},
onEachFeature: function (feature, layer) {
var popup = L.popup();
layer.on('click', function (e) {
var deferred = $.Deferred();
popup.setLatLng(e.latlng);
popup.setContent(new TableContent(feature.properties));
popup.openOn(map);
deferred.resolve();
});
}
});
var myStyle = {
weight: 2,
opacity: 1,
color: '#FF0000',
dashArray: '3',
fillOpacity: 0.3,
fillColor: '#FA8072'
};
var wayBuild = L.geoJson(null, {
style: myStyle,
onEachFeature: function (feature, layer) {
var popup = L.popup();
layer.on('click', function (e) {
var deferred = $.Deferred();
popup.setLatLng(e.latlng);
popup.setContent(new TableContent(feature.properties));
popup.openOn(map);
deferred.resolve();
});
}
});
function pointLinePolygon(receivedPoints, receivedLines, receivedPolygon, day) {
var points_, lines_, polygon_;
var deferredPoint = $.Deferred();
var deferredLine = $.Deferred();
var deferredPolygon = $.Deferred();
$.getJSON(receivedPoints, function (data) {
setTimeout(function () {
pointBuild.addData(data);
points_ = markerCluster;
deferredPoint.resolve();
}, 0);
});
$.getJSON(receivedLines, function (data) {
setTimeout(function () {
lines_ = wayBuild.addData(data);
deferredLine.resolve();
}, 0);
});
$.getJSON(receivedPolygon, function (data) {
setTimeout(function () {
polygon_ = wayBuild.addData(data);
deferredPolygon.resolve();
}, 0);
});
$.when(deferredPoint, deferredLine, deferredPolygon).done(function () {
var featureGroup = L.layerGroup([points_, lines_, polygon_]);
featureGroup.addTo(map);
$.map(wayBuild._layers, function (layer, index) {
$(layer._container).find("path").attr("title", "This is a way feature. Click to have a look at some of its attributes.");
});
});
}
map.on('cluster-hover', function () {
setTimeout(function () {
$("#map").find("div.marker-cluster").attrByFunction(function () {
return {
title: "This is a Cluster of " + $(this).find("span").text() + " Point features. Click to zoom in and see the Point features and sub-clusters it contains."
}
});
}, 0);
});
var tooltip = $('<div id="toolTipSlider" />').hide();
$('#slider').slider({
min: 1,
max: 4,
slide: function (event, ui) {
if (ui.value === 1) {
tooltip.text("Day " + ui.value);
$.ajax({
type: 'post',
success: function () {
pointLinePolygon("data/day1/points.geojson", "data/day1/lines.geojson", "data/day1/polygon.geojson", "Day 1");
}
});
}
else if (ui.value === 2) {
tooltip.text("Day " + ui.value);
$.ajax({
type: 'post',
success: function () {
pointLinePolygon("data/day2/points.geojson", "data/day2/lines.geojson", "data/day2/polygon.geojson", "Day 2");
}
});
}
else if (ui.value === 3) {
tooltip.text("Day " + ui.value);
$.ajax({
type: 'post',
success: function () {
pointLinePolygon("data/day3/points.geojson", "data/day3/lines.geojson", "data/day3/polygon.geojson", "Day 3");
}
});
}
else if (ui.value === 4) {
tooltip.text("Day " + ui.value);
$.ajax({
type: 'post',
success: function () {
pointLinePolygon("data/day4/points.geojson", "data/day4/lines.geojson", "data/day4/polygon.geojson", "Day 4");
}
});
}
}
}).find(".ui-slider-handle").append(tooltip).hover(function () {
tooltip.show();
});
});
$.fn.attrByFunction = function (a) {
return $(this).each(function () {
$(this).attr(a.call(this));
});
};
I solved the problem by clearing the map layer every time I am to add new one.
map.eachLayer(function (layer) {
if (layer.feature) {
map.removeLayer(layer);
}
});
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.
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..