Need Google Maps to open Multiple Marker Popups with Fancybox - javascript

I am creating a Google map with multiple markers that I want to popup into a Fancybox lightbox when clicked on. I must admit, I am quite a novice at javascript and Google Maps API.
I have put some pieces of different sample scripts together and come up with something that actually works decently. I have the markers the way I want them (well, without captions... which I still have to figure out), the style of map the way I want it, and I even have the markers popping up lightboxes when clicked on.
However, all markers end up opening one URL in the lightbox. I guess that makes a bit of sense. The Fancybox code is being distributed to all the markers, instead of each one individually. I tried to make another argument with a url and pass it into the Fancybox script, but it still just picks up the last marker's url and uses it for all the markers. How would I be able to get the URL to work for each marker instead of all the markers at once?
I did find a similar question on here:
Multiple fancybox google map
However, it seams to use a different route of attacking the same issue. Plus, I can't seem to get their script to work by itself, let alone integrate it with my code. So, while I get how the solution works for them, it doesn't seem to help me.
My code is as follows:
var map;
var MY_MAPTYPE_ID = 'custom_style';
function initialize() {
var featureOpts = [
{
stylers: [
{ hue: '#CCCCCC' },
{ saturation: '-100' },
{ visibility: 'simplified' },
{ gamma: 2 },
{ weight: .4 }
]
},
{
elementType: 'labels',
stylers: [
{ visibility: 'off' }
]
},
{
featureType: 'water',
stylers: [
{ color: '#efefef' }
]
}
];
var mapOptions = {
zoom: 9,
scrollwheel: false,
keyboardShortcuts: false,
disableDefaultUI: true,
center: new google.maps.LatLng(34.0531553, -84.3615928),
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, MY_MAPTYPE_ID]
},
mapTypeId: MY_MAPTYPE_ID
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var styledMapOptions = {
name: 'Custom Style'
};
var customMapType = new google.maps.StyledMapType(featureOpts, styledMapOptions);
map.mapTypes.set(MY_MAPTYPE_ID, customMapType);
setMarkers(map, schools);
}
var schools = [
['Canton', 34.2352063, -84.4846274, 4, 'popup.htm'],
['Austell', 33.8158106, -84.6334938999999, 3, 'popup.htm'],
['Marietta', 33.9578674, -84.5532791, 2, 'popup.htm'],
['Atlanta', 33.7635085, -84.43030209999999, 1, 'popup2.htm']
];
function setMarkers(map, locations) {
var image = {
url: 'images/fml-home.png',
size: new google.maps.Size(67, 63),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(0, 63)
};
var shadow = {
url: 'images/fml-shadow.png',
size: new google.maps.Size(45, 18),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(0, 18)
};
var shape = {
coord: [1, 1, 1, 67, 60, 67, 60 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var schools = locations[i];
var myLatLng = new google.maps.LatLng(schools[1], schools[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
shadow: shadow,
icon: image,
shape: shape,
title: schools[0],
zIndex: schools[3]
});
var href = schools[4];
google.maps.event.addListener(marker, 'click', function() {
$.fancybox({
frameWidth : 800,
frameHeight : 600,
href : href,
type : 'iframe'
});
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);

Try this:
marker["href"] = schools[4];
google.maps.event.addListener(marker, 'click', function() {
$.fancybox({
frameWidth : 800,
frameHeight : 600,
href : this.href,
type : 'iframe'
});
});

Related

How do I get "Hide/Show" and "add marker" functions to work together in Google maps?

I am trying to create a page for my family tree website containing a google map with two additions (i) to add markers to show places linked to the family, and (ii) to "hide/show" Google's poi markers.
By copying and pasting, I have managed to code an HTML page with one combined script which, when opened, only shows the "add marker" element. If I delete the "add marker" section of code I get the "Hide/Show" element only (as you would expect). Never both of them at the same time on the same map!
I strongly suspect that it has something to do with the fact I have duplicated the "function initMap" and "var map" commands, but if I delete one pair of these commands, I just get a blank page.
I have spent the last few days searching google maps API and the internet generally with no success, and it is driving me mad.
Can any of you good people out there share your knowledge and tell me where I am going wrong? As you may guess, this is my first venture into Javascript!!
THIS PROBLEM HAS NOW BEEN SOLVED AND THE WORKING CODE IS NOW SHOWN HERE:-
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7, center: { lat: 52.85, lng: 1.16 },
});
var styleControl = document.getElementById('style-selector-control'); map.controls[google.maps.ControlPosition.TOP_CENTER].push(styleControl);
document.getElementById('hide-poi').addEventListener('click', function () {
map.setOptions({ styles: styles['hide'] });
});
document.getElementById('show-poi').addEventListener('click', function () {
map.setOptions({ styles: styles['default'] });
});
var styles = {
default: null,
hide: [
{
featureType: 'poi',
stylers: [{visibility: 'off'}]
},
{
featureType: 'transit',
elementType: 'labels.icon',
stylers: [{visibility: 'off'}]
}
]
}
var marker = new google.maps.Marker({
position: {lat:52.05,lng:1.16},
map: map,
title: 'Hello World!'
});
}
</script>
Just add the marker(s) inside of the first mapInit(), get rid of the second:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: { lat: 53.82, lng: -4.74 },
});
var styleControl = document.getElementById('style-selector-control');
map.controls[google.maps.ControlPosition.TOP_CENTER].push(styleControl);
document.getElementById('hide-poi').addEventListener('click', function () {
map.setOptions({ styles: styles['hide'] });
});
document.getElementById('show-poi').addEventListener('click', function () {
map.setOptions({ styles: styles['default'] });
});
var marker = new google.maps.Marker({
position: { lat: 53.82, lng: -4.74 },
map: map,
title: 'Hello World!'
});
}

Map not showing first time I enter in the screen

The following html code loads a google map:
<div> Map :
<div ng-controller = "CreateNewEvent" id="map" style="width: 100%; height: 400px" data-tap-disabled="true" ng-init="initMap()"> </div>
</div>
which refers to the angular code:
// initialization of the map
$scope.initMap = function() {
$ionicLoading.show({
template: '<p>Loading...</p><ion-spinner icon="spiral" class="spinner-balanced"></ion-spinner>'
})
$scope.googleMap().then(function(results){
var latLng = results.latLng;
var map = results.map;
var marker = new google.maps.Marker({
position: latLng,
visible:true,
Map: map,
Icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png' //personalize with icon
});
$timeout(function(){
alert('timeout')
$scope.$apply();
$ionicLoading.hide();
})
})
}
$scope.SetLatLong = function(){
var deferred = $q.defer()
alert('coords'+$scope.lat+'--'+$scope.long)
// geo coordinates
if($scope.lat!=undefined && $scope.long!=undefined){
var latLng = new google.maps.LatLng($scope.lat, $scope.long);
alert('lat'+JSON.stringify(latLng))
deferred.resolve(latLng);
return deferred.promise
} else {
alert('latelse')
var latLng = new google.maps.LatLng(51.5074, 0.1278)//London
deferred.resolve(latLng);
return deferred.promise
}
}
$scope.SetMapOptStyle = function(latLng){
var deferred1 = $q.defer()
var mapOptions = {
center: latLng,
zoom: 17,
disableDefaultUI: true,
clickableIcons: false,
disableDoubleClickZoom: true,
draggable: false,
keyboardShortcuts: false,
};
var styledMapType = new google.maps.StyledMapType(
[{
stylers: [
{ hue: '#00ffe6' },
{ saturation: -20 }
]
},{
featureType: 'road',
elementType: 'geometry',
stylers: [
{lightness: 100 },
{visibility: 'simplified' }
]
},{
featureType: 'road',
elementType: 'labels',
stylers: [
{ visibility: 'off' }
]
}],{
name: 'Styled Map'}
);
deferred1.resolve([mapOptions,styledMapType])
return deferred1.promise
}
// initialization of the map
$scope.googleMap = function() {
alert('googleMap')
// initilization of variables
var deferred = $q.defer()
var map1;
var latLng;
var mapOptions;
var styledMapType;
return $scope.SetLatLong().then(function(res){
latLng = res
return $scope.SetMapOptStyle(latLng).then(function(res1){
mapOptions = res1[0]
styledMapType = res1[1]
// map creation
map1 = new google.maps.Map(document.getElementById('map'), mapOptions);
// other options associated to the map style
map1.mapTypes.set('styled_map', styledMapType);
map1.setMapTypeId('styled_map');
// promise output
var results = {'map':map1,'latLng':latLng}
//alert('map--'+JSON.stringify(map1))
//alert('latlong--'+JSON.stringify(latLng))
deferred.resolve(results);
//return deferred.promise
return results
})
})
}
the problem is on the first time I load the screen. It seems that the map is loaded on the $scope of the previous screen so when the screen is loaded the map is missing. However if I refresh the page the map is correctly loaded in the page (so in the $scope). Maybe 'document.getElementById('map')' refers to the current page before refreshing? Any idea?
I found the solution: the screen that calls the map page contains itself a map. Both maps in the two pages refer to the same div id like:
<div> Map :
<div ng-controller = "CreateNewEvent" id="map" style="width: 100%; height: 400px" data-tap-disabled="true" ng-init="initMap()"> </div>
so id='map' in both screens. I did changed the id to 'map_edit' in one of the two screens and now the map is showing correctly (also document.getElementById('div_id') needs to be changed accordingly) . I think the problem is due to the refreshing of the page which is done after the map function initMap is called.

How to get the fired marker using event.addListener with Google Map API v3

I have a simple Google Map with some markers added looping on a json object.
I'm trying to add a listener to all of these markers to do a simple action (change the rotation). Markers are added on map and listener is called, but when i click on one of the markers, the action is performed always on the latest added.
How I can get the fired marker? I think that the way is to use the evt parameter of the listener function, but I don't know how.
I watched inside the evt parameter with firebug but without results.
Here is the code:
for(var i in _points){
_markers[i] = new google.maps.Marker({
position: {
lat: parseFloat(_points[i]._google_lat),
lng: parseFloat(_points[i]._google_lon)
},
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
rotation: parseInt(_points[i]._rotation)
},
map: _map,
title: _points[i]._obj_id
});
google.maps.event.addListener(_markers[i], 'click', function(evt){
//console.log(evt);
r = _markers[i].icon.rotation;
_markers[i].setIcon({
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
rotation: r+15
});
});
}
The this inside the click listener function is a reference to the marker:
google.maps.event.addListener(_markers[i], 'click', function(evt){
//console.log(evt);
r = this.getIcon().rotation;
this.setIcon({
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
rotation: r+15
});
});
proof of concept fiddle
code snippet:
function initMap() {
// Create a map and center it on Manhattan.
var _map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: 40.771,
lng: -73.974
}
});
for (var i in _points) {
_markers[i] = new google.maps.Marker({
position: {
lat: parseFloat(_points[i]._google_lat),
lng: parseFloat(_points[i]._google_lon)
},
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
rotation: parseInt(_points[i]._rotation)
},
map: _map,
title: _points[i]._obj_id
});
google.maps.event.addListener(_markers[i], 'click', function(evt) {
r = this.getIcon().rotation;
this.setIcon({
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
rotation: r + 15
});
});
}
}
google.maps.event.addDomListener(window, "load", initMap);
var _markers = [];
var _points = [{
_google_lat: 40.7127837,
_google_lon: -74.0059413,
_obj_id: "A",
_rotation: 0
}, {
_google_lat: 40.735657,
_google_lon: -74.1723667,
_obj_id: "B",
_rotation: 90
}]
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

street view and googlemaps

Im trying to solve a problem. I have a map locating parking and would like to put the street view. I got a place, but the array of "locations" does not work completely. The map shows only the last array in the street view (ps: you must click the icon to display the street view)
http://www.clicrbs.com.br/sites/swf/paulMapa/mapspaul.html
function initialize() {
var pinkParksStyles = [
{
featureType: "all",
stylers: [
{ saturation: -80 }
]
},
{
featureType: "poi.park",
stylers: [
{ hue: "#ff0023" },
{ saturation: 40 }
]
}
];
var pinkMapType = new google.maps.StyledMapType(pinkParksStyles,
{name: "Paul em Floripa"});
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(-27.619279,-48.527896),
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP,'pink_parks','satellite' ],
streetViewControl: true
}
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker();
var infowindow = new google.maps.InfoWindow();
var kmlLayer = new google.maps.KmlLayer('http://www.clicrbs.com.br/sites/swf/paulMapa/trajetoComum.kml');
var locations = [
['Estacionamento 1', -27.626216,-48.526806, 1],
['Estacionamento 2', -27.622654,-48.528102, 2],
['Estacionamento 3', -27.618236,-48.528598, 3],
['Estacionamento 4', -27.615011,-48.529491, 4],
['Estacionamento 5', -27.613015,-48.532554, 5],
['Estacionamento 6', -27.612033,-48.534453, 6],
['Estacionamento 7', -27.611326,-48.530995, 7],
['Estacionamento 8', -27.613811,-48.527514, 8],
];
var pano = null;
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
icon: 'images/stopcar.png',
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))
google.maps.event.addListener(infowindow, 'domready', function() {
if (pano != null) {
pano.unbind("position");
pano.setVisible(false);
}
pano = new google.maps.StreetViewPanorama(document.getElementById("content"), {
navigationControl: true,
enableCloseButton: true,
addressControl: true,
linksControl: false,
});
pano.bindTo("position", marker);
pano.setVisible(true);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
pano.unbind("position");
pano.setVisible(true);
pano = null;
});
}
kmlLayer.setMap(map);
map.mapTypes.set('pink_parks', pinkMapType);
map.setMapTypeId('pink_parks');
map.setStreetView(pano);
}
​
I decided
function initialize() {
var pinkParksStyles = [
{
featureType: "all",
stylers: [
{ saturation: -80 }
]
},
{
featureType: "poi.park",
stylers: [
{ hue: "#ff0023" },
{ saturation: 40 }
]
}
];
// Create the map
// No need to specify zoom and center as we fit the map further down.
var pinkMapType = new google.maps.StyledMapType(pinkParksStyles,
{name: "Paul em Floripa"});
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(-27.619279,-48.527896),
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP,'pink_parks','satellite' ],
streetViewControl: true
}
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var kmlLayer = new google.maps.KmlLayer('http://www.clicrbs.com.br/sites/swf/paulMapa/trajetoComum.kml');
// Define the list of markers.
// This could be generated server-side with a script creating the array.
var markers = [
{ lat:-27.626216, lng:-48.526806, name:"Estacionamento 1"},
{ lat:-27.622654, lng:-48.528102, name:"Estacionamento 2"},
{ lat:-27.618236, lng:-48.528598, name:"Estacionamento 3"},
{ lat:-27.615011, lng:-48.529491, name:"Estacionamento 4"},
{ lat:-27.613015, lng:-48.532554, name:"Estacionamento 5"},
{ lat:-27.612033, lng:-48.534453, name:"Estacionamento 6"},
{ lat:-27.611326, lng:-48.530995, name:"Estacionamento 7"},
{ lat:-27.613811, lng:-48.527514, name:"Estacionamento 8"},
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
icon: 'images/stopcar.png',
map: map,
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.name;
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "400px";
streetview.style.height = "400px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: true,
enableCloseButton: true,
addressControl: true,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
map.mapTypes.set('pink_parks', pinkMapType);
map.setMapTypeId('pink_parks');
kmlLayer.setMap(map);
}

Google Maps V3 Map not loaded when adding listener

I am trying to add an idle listener to google maps.
Problem: When I added the listener as shown below, I get the error Cannot read property '__e3_' of undefined
JS Code
google.maps.event.addListener(map, 'idle', function() {
console.log('hello');
}
I solved it by adding a setTimeout(..., 1000), to make sure the map is loaded after a sec.
Question:
Is the error due to the map not being loaded?
Is this the best way to solve it?
Is this problem supposed to occur? I am guessing that if I added this same listener to map without other code, this error will not popup.
EDIT
Initialization of Map
<script type="text/javascript">
var map;
var geocoder;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var center_latlng = new google.maps.LatLng(42.354183,-71.065063);
var options = {
zoom: 15,
minZoom: 11,
maxZoom: 19,
center: center_latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), options);
var Style = [
{
featureType: "poi",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
},{
featureType: "landscape",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
]
map.setOptions({styles: Style});
geocoder = new google.maps.Geocoder();
// Marker Clusterer
var styles = {styles: [{
height: 34,
url: "images/template/markers/cluster.png",
width: 34,
textColor: '#FFF',
textSize: 12
},
{
height: 56,
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m2.png",
width: 56
},
{
height: 66,
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m3.png",
width: 66
},
{
height: 78,
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m4.png",
width: 78
},
{
height: 90,
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m5.png",
width: 90
}]
};
var mcOptions = {gridSize: 50, maxZoom: 15, styles: styles['styles']};
mc = new MarkerClusterer(map, [], mcOptions);
}
</script>
1.) Not exactly, This type of error is occurring because you are trying to access an object that doesn't exist at the time you try to attach the listener. The listener code must be attached after the map variable contains the Google map object. When are you trying to attach the listener? I do not see it in the initialization code.
2.) No, timeouts are not reliable. If there is a delay in the initialization the map object may still not be initialized at the specified interval.
3.) You can not access properties of an object that doesn't exist. Adding the listener in the init method after the map object is instantiated will solve this problem.
var map;
function initialize() {
var center_latlng = new google.maps.LatLng(42.354183, -71.065063);
var options = {
zoom: 15,
minZoom: 11,
maxZoom: 19,
center: center_latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//instantiate map object
map = new google.maps.Map(document.getElementById("map_canvas"), options);
//attach listener to the map object.
google.maps.event.addListener(map, 'idle', function() {
console.log('hello');
});
}
here is a working fiddle with the above code: http://jsfiddle.net/R7d6L/

Categories

Resources