Static infowindow with Google Maps V3 (disable events temporarily) gmap3 - google-maps

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);
}
});
}

Related

Issue to set map in center so multiple marker display

i am using ionic framework. i created map and multiple markers and value came from server side.all data came properly but i don't know why i getting this error-
ionic.bundle.js:25642 TypeError: Cannot read property 'fitBounds' of null
at autoCenter (app.js:147)
at app.js:135
at processQueue (ionic.bundle.js:27879)
at ionic.bundle.js:27895
at Scope.$eval (ionic.bundle.js:29158)
at Scope.$digest (ionic.bundle.js:28969)
at Scope.$apply (ionic.bundle.js:29263)
at done (ionic.bundle.js:23676)
at completeRequest (ionic.bundle.js:23848)
at XMLHttpRequest.requestLoaded (ionic.bundle.js:23789)
code :
angular.module('starter', ['ionic', 'ngCordova'])
.run(function ($ionicPlatform, GoogleMaps) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
GoogleMaps.init();
});
})
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('map', {
url: '/',
templateUrl: 'templates/map.html',
controller: 'MapCtrl'
});
$urlRouterProvider.otherwise("/");
})
.factory('Markers', function ($http) {
var markers = [];
return {
getMarkers: function () {
return $http.get("http://localhost:8080/LocationServices/markers.php").then(function (response) {
markers = response;
return markers;
});
}
}
})
.factory('GoogleMaps', function ($cordovaGeolocation, Markers) {
var apiKey = false;
var map = null;
var zoomVal = 15
function initMap() {
var options = { timeout: 10000, enableHighAccuracy: true };
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
console.log("Latitude current: ", position.coords.latitude);
console.log("Longitude current: ", position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: zoomVal,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//Wait until the map is loaded
google.maps.event.addListenerOnce(map, 'idle', function () {
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: latLng
});
//Load the markers
loadMarkers(map);
//map.setCenter(new google.maps.LatLng(-37.92, 151.25));
});
}, function (error) {
console.log("Could not get location");
//Load the markers
loadMarkers(map);
//map.setCenter(new google.maps.LatLng(-37.92, 151.25));
});
}
function loadMarkers(map) {
//Get all of the markers from our Markers factory
Markers.getMarkers().then(function (markers) {
console.log("Markers: ", markers);
var markersss = new Array();
var records = markers.data.markers;
for (var i = 0; i < records.length; i++) {
var record = records[i];
console.log("Latitude: ", record.lat);
console.log("Longitude: ", record.lng);
var markerPos = new google.maps.LatLng(record.lat, record.lng);
console.log("marker position", "" + markerPos);
// Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
markersss.push(marker);
var infoWindowContent = "<h4>" + record.name + "</h4>";
addInfoWindow(marker, infoWindowContent, record);
}
autoCenter(map, markersss);
});
}
function autoCenter(map1, markersss) {
//Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
//Go through each...
for (var i = 0; i < markersss.length; i++) {
bounds.extend(markersss[i].position);
console.log("bounds position", "" + markersss[i].position);
}
//Fit these bounds to the map
map1.fitBounds(bounds);
map1.setCenter(bounds.getCenter());
//remove one zoom level to ensure no marker is on the edge.
map1.setZoom(vm.googleMap.getZoom() - 1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if (map1.getZoom() > zoomVal) {
map1.setZoom(zoomVal);
}
}
function addInfoWindow(marker, message, record) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
return {
init: function () {
initMap();
}
}
})
.controller('MapCtrl', function ($scope, $state, $cordovaGeolocation) {
});
The map will only be created when $cordovaGeolocation.getCurrentPosition was successfull, but you also call loadMarkers when it wasn't successfull(map is null in this case)
Solution: create the map outside of the getCurrentPosition-callbacks (with a default-value for center).
In the success-callback create the marker and set the center of the map
function initMap() {
var options = { timeout: 10000, enableHighAccuracy: true },
mapOptions = {
center: new google.maps.LatLng(-37.92,151.25),
zoom: zoomVal,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function () {
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var center = new google.maps.LatLng( position.coords.latitude,
position.coords.longitude);
map.setCenter(center);
new google.maps.Marker({
map : map,
animation : google.maps.Animation.DROP,
position : center
});
loadMarkers(map);
}, function (error) {
loadMarkers(map);
});
});
}

How to remove previous shape when drawing new shape is started on Google Map

I am currently working on a map-based web application. Previous rectangle (or polygon) that is already drawn should be deleted before I draw new rectangle by drawing layer tool on Google Map.
There is "overlaycomplete" event on Google Map, but if I use it, previous rectangle is removed after drawing new rectangle is completed(mouse-up). However, I need to remove previous rectangle before process of drawing new rectangle starts(mouse-down). Two rectangle should not be seen at the same time on the map!
All feedbacks appreciated!
Here is jsFiddle! - http://jsfiddle.net/sean35/41Lrcq7L/30/
Example code:
function initialize() {
var centerInfo = document.getElementById("mainForm:centerInfo").value;
var zoomInfo = document.getElementById("mainForm:zoomInfo").value;
centerInfo = centerInfo.split(",");
var mapOptions = {
center : {
lat : parseFloat(centerInfo[0]),
lng : parseFloat(centerInfo[1])
},
zoom : parseInt(zoomInfo)
};
map = new google.maps.Map(document.getElementById('deviceControlMap'), mapOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
// drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl : true,
drawingControlOptions : {
position : google.maps.ControlPosition.TOP_CENTER,
drawingModes : [
// google.maps.drawing.OverlayType.POLYGON,
google.maps.drawing.OverlayType.RECTANGLE ]
},
rectangleOptions : {
strokeWeight : 1,
clickable : true,
editable : false,
zIndex : 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
if (event.type == google.maps.drawing.OverlayType.RECTANGLE) {
if(rectangle != null)
rectangle.setMap(null);
closeDimSubWin();
rectangle = event.overlay;
var bounds = rectangle.getBounds();
console.log(bounds);
}
});
google.maps.event.addListener(drawingManager, "drawingmode_changed", function() {
if(rectangle != null)
rectangle.setMap(null);
});
// when the user clicks somewhere else on the map.
google.maps.event.addListener(map, 'click', function() {
if(rectangle != null)
rectangle.setMap(null);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
EDIT: I wrote two similar question before. But I deleted them and wrote this question with extended information. I hope that the question is understandable.
One option:
set the drawing mode to null on rectanglecomplete
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
if (event.type == google.maps.drawing.OverlayType.RECTANGLE) {
if(rectangle != null)
rectangle.setMap(null);
rectangle = event.overlay;
var bounds = rectangle.getBounds();
console.log(bounds);
drawingManager.setDrawingMode(null);
}
});
remove the rectangle when it is changed back to RECTANGLE
google.maps.event.addListener(drawingManager, "drawingmode_changed", function() {
if ((drawingManager.getDrawingMode() == google.maps.drawing.OverlayType.RECTANGLE) &&
(rectangle != null))
rectangle.setMap(null);
});
updated fiddle
code snippet:
/*
* declare map as a global variable
*/
var map;
var rectangle = null;
/*
* use google maps api built-in mechanism to attach dom events
*/
google.maps.event.addDomListener(window, "load", function() {
var mapOptions = {
center: new google.maps.LatLng(33.808678, -117.918921),
zoom: 4,
};
map = new google.maps.Map(document.getElementById('deviceControlMap'), mapOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
// drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
// google.maps.drawing.OverlayType.POLYGON,
google.maps.drawing.OverlayType.RECTANGLE
]
},
rectangleOptions: {
strokeWeight: 1,
clickable: true,
editable: false,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
if (event.type == google.maps.drawing.OverlayType.RECTANGLE) {
if (rectangle != null)
rectangle.setMap(null);
rectangle = event.overlay;
var bounds = rectangle.getBounds();
console.log(bounds);
drawingManager.setDrawingMode(null);
}
});
google.maps.event.addListener(drawingManager, "drawingmode_changed", function() {
if ((drawingManager.getDrawingMode() == google.maps.drawing.OverlayType.RECTANGLE) &&
(rectangle != null))
rectangle.setMap(null);
});
// when the user clicks somewhere else on the map.
google.maps.event.addListener(map, 'click', function() {
if (rectangle != null)
rectangle.setMap(null);
});
});
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
<div id="deviceControlMap" style="height: 400px;"></div>

change google maps custom image marker depending on zoom level

I'm using mosne map (www.mosne.it/playground/mosne_map)
What I'm trying to do is, whenever user change zoom level < 10 the image will be changed. Here's what I got now:
currently the marker doesn't change whenever user changes zoom level
$.fn.mosne_map = function (options) {
var baseconf = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var s_infobox = {
content: "",
disableAutoPan: false,
maxWidth: 0,
pixelOffset: new google.maps.Size(-110, 5),
zIndex: null,
boxStyle: {
background: "url('images/infobox_top.png') top center no-repeat",
opacity: 1,
color: '#fff',
padding: '0',
width: "300px"
},
closeBoxMargin: "16px 4px",
closeBoxURL: "images/infobox_close_hd2.png",
infoBoxClearance: new google.maps.Size(1, 1),
isHidden: false,
pane: "floatPane",
enableEventPropagation: false
};
defaults = {
elements: '#list .maplocation', //links selector
map_opt: baseconf, // custom map options object
clat: -9.460181, // set the lat default map center
clng: 100.988281, // set the lng default map center
mapstyle_name: '', // custom map style label and id
mapstyle: '', // mapstyle object
cluster_styles: {}, // custom cluster icons object
marker_icon: {}, // custom marker icon url,width,height
infowindows: true, // shows infoWindows grabing html from the .infobox element
infobox: false, // enable custom infoWindows using infobox class
infobox_s: s_infobox, // default color scheme for custom infobox container
trigger: 'map_open', // you can set a event trigger for each link/marker
clickedzoom: 15, // set the zoom level when you click the single marker
timeout: 100, // delay between click and zoom on the single marker
mode: 'latlng', // switch mode
wait: 500, // timeout between geocode requests
maxtry: 10, // limit of time to bypass query overlimit
cat_style: {}, // costum icons and click zoom level
fitbounds: false, // on|off fit bounds
defzoom: 3, // default zoom level if fitbounds is off
showzoom: false, // bind current map zoom level event
before: function () {}, // before create map callback
after: function () {}, // after create map callback
afterUpdate: function () {} // after update map callback
};
var settings = $.extend({}, defaults, options);
this.each(function () {
var map_el = $(this);
var the_map_el = $(this).get(0);
//on before
settings.before.apply(map_el);
//init map
var center = new google.maps.LatLng(settings.clat, settings.clng);
var map = new google.maps.Map(the_map_el, settings.map_opt);
var bounds = new google.maps.LatLngBounds();
var markerCluster = new MarkerClusterer(map, null, settings.cluster_styles);
map.setCenter(center);
bounds.extend(center);
map.setZoom(settings.defzoom);
map.setCenter(center);
//apply map style
if (settings.mapstyle_name != '') {
var styledMapOptions = {
name: settings.mapstyle_name
};
var m_MapType = new google.maps.StyledMapType(settings.mapstyle, styledMapOptions);
map.mapTypes.set(settings.mapstyle_name, m_MapType);
map.setMapTypeId(settings.mapstyle_name);
}
// set markers icons
var markerIcon = new google.maps.MarkerImage("http://googlemaps.googlermania.com/img/google-marker-big.png");
// init infowindow
if (settings.infowindows) {
var infowindow = new google.maps.InfoWindow({
maxWidth: 200
});
}
// init infobox
if (settings.infobox) {
var boxText = document.createElement("div");
boxText.style.cssText = settings.infobox_s_txt
boxText.innerHTML = "hello world";
var m_box = new InfoBox(settings.infobox_s);
}
// function create marker
var _createMarker = function (el, latLng, markerIcon, m_name, cat) {
if (cat) {
var c_icon = settings.cat_style[cat]['icon'];
var c_icon_w = settings.cat_style[cat]['width'];
var c_icon_h = settings.cat_style[cat]['height'];
if (c_icon) { //var markerIcon = c_icon;
var markerIcon = new google.maps.MarkerImage(c_icon, null, null, null, new google.maps.Size(c_icon_w, c_icon_h));
}
}
var marker = new google.maps.Marker({
position: latLng,
icon: markerIcon,
flat: true,
title: m_name
});
//extend bounds
bounds.extend(latLng);
// bind click on map trigger event fill infowindow / infobox content on demand
if (settings.infowindows || settings.infobox) {
var content = el.find('.infobox').html();
}
google.maps.event.addListener(marker, 'click', function () {
if (settings.infowindows) {
infowindow.close();
infowindow.setContent(content);
infowindow.open(map, marker);
map.setCentexxxr(marker.getPosition());
}
if (settings.infobox) {
m_box.close();
$(boxText).hide();
m_box.setContent(content);
m_box.open(map, marker);
$(boxText).show("slow");
map.setCentesr(marker.getPosition());
}
el.trigger(settings.trigger);
$(el).parent().find('.active').removeClass('active');
$(el).addClass('active');
setTimeout(function () {
map.setZoom(settings.clickedzoom);
map.panTo(latLng);
marker.setAnimation(google.maps.Animation.DROP);
}, settings.timeout);
});
// trigger click on list
$(el).find('.maplink').unbind("click").bind("click", function (e) {
e.preventDefault();
google.maps.event.trigger(marker, "click");
return false;
});
markerCluster.addMarker(marker);
};
var _m_geocode = function (el, geocoder, address, name, cat, j) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLng = results[0].geometry.location;
_createMarker(el, latLng, markerIcon, name, cat);
if (settings.fitbounds === true) {
map.fitBounds(bounds);
}
} else {
if (status === "OVER_QUERY_LIMIT") {
setTimeout(function () {
//console.log("trying again "+g_address);
j++;
if (j <= settings.maxtry) {
_m_geocode(el, geocoder, address, name, cat, j);
} else {
$(el).css({
opacity: .35
});
}
}, settings.wait);
} else if (status === "ZERO_RESULTS") {
$(el).css({
opacity: .35
});
}
}
});
}
//
$(map_el).bind('update', function () {
//reset cluster and bounds
markerCluster.clearMarkers();
bounds = null;
bounds = new google.maps.LatLngBounds();
// markers loop
var markers = [];
var w_delay = 0;
if (settings.mode === 'address') {
var geocoder = new google.maps.Geocoder();
}
var totel = $(settings.elements).length;
$(settings.elements).each(function (i) {
// create marker
var el = $(this);
//mode geocoding
if (settings.mode === 'address') {
var mkr = el.data();
var name = $(this).find(".name").text();
var address = $(this).find(".address").text();
setTimeout(function () {
_m_geocode(el, geocoder, address, name, mkr.cat, 0);
}, settings.wait * i);
} else {
// mode latlng
var mkr = el.data();
var latLng = new google.maps.LatLng(mkr.lat, mkr.lng);
_createMarker(el, latLng, markerIcon, mkr.name, mkr.cat);
}
//end of the elements loop
});
if (settings.fitbounds === true) {
// log(bounds);
map.fitBounds(bounds);
if (totel == 1) {
map.setZoom(settings.clickedzoom);
}
if (totel == 0) {
map.setZoom(settings.defzoom);
map.setCenter(center);
}
// map.setCenter(center);
} else {
//map.setZoom(settings.defzoom);
//map.setCenter(center);
};
//callbak afterUpdate
settings.afterUpdate.apply(map_el);
}).trigger('update');
$(map_el).bind('bounds', function () {
map.fitBounds(bounds);
});
// nice zoom status
if (settings.showzoom) {
google.maps.event.addListener(map, 'zoom_changed', function () {
$(map_el).trigger("showzoom", [map.getZoom()]);
});
};
//on after
settings.after.apply(map_el);
return true;
//change markerIcon
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoom = map.getZoom();
if (zoom <= 10) {
var markerIcon = new google.maps.MarkerImage("http://i.stack.imgur.com/B2Vg5.png");
}
else {
var markerIcon = new google.maps.MarkerImage ("http://googlemaps.googlermania.com/img/google-marker-big.png")
}
});
});
};
A simple solution for a single icon(not a single marker, this method will change the icon of all markers, but there is also an option to define category-markers)
This is the code that currently defines the default-icon:
// set markers icons
var markerIcon = new google.maps.MarkerImage("http://googlemaps.googlermania.com/img/google-marker-big.png");
Replace it with this code:
// set markers icons
var markerIcon = new google.maps.MVCObject();
google.maps.event.addListener(map,'zoom_changed',function(){
markerIcon.set('icon',(this.getZoom()<10)
? 'http://www.google.com/mapfiles/marker.png'//url for zoom<10
: 'http://googlemaps.googlermania.com/img/google-marker-big.png'//url for zoom>=10
);
});
google.maps.event.trigger(map,'zoom_changed',{});
The url of markerIcon now will be updated when the zoom changes
To apply the changes to the markers replace this code:
var marker = new google.maps.Marker({
position: latLng,
icon: markerIcon,
flat: true,
title: m_name
});
with.....
var marker = new google.maps.Marker({
position: latLng,
icon: markerIcon.icon,
flat: true,
title: m_name
});
marker.bindTo('icon',markerIcon,'icon') ;

show google map inside a jquery dialogue form

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 :)

jquery-ui-map load json and update markers

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..