Google Maps InfoWindow Open When Only One Marker is Present - javascript

I am taking an Advanced Custom Fields (ACF) Google Map Address and creating a Google Map with multiple markers and a singular InfoWindow. The contents of that InfoWindow are then swapped depending on which marker is active.
A PHP $location array is setup through ACF, and the javascript loops through and runs to the Google Maps API.
I want to open the InfoWindow by default when there is only one marker.
I have figured out how to determine if there is only one marker at the end of the new_map function…
if($markers.length == 1) {
console.log('yes');
}
But I am unsure of what to call/how to access the Google Maps API once the map has already been rendered.
I think my issue is scope related, as I've tried every combination of google.maps.event.trigger() and google.maps.Map.event.trigger(marker, 'click'); style functions I can think of.
Array
(
[address] => 123 Hamaker Rd, Manheim, PA, United States
[lat] => 40.1789636
[lng] => -76.3852963
)
<script type="text/javascript">
(function($) {
/*
* new_map
*
* This function will render a Google Map onto the selected jQuery element
*
* #type function
* #date 8/11/2013
* #since 4.3.0
*
* #param $el (jQuery element)
* #return n/a
*/
/*
* Modified from ACF Documentation, here are some links
* http://support.advancedcustomfields.com/forums/topic/multiple-post-points-on-google-maps/
* http://fancysquares.com/google-maps-infowindow-advanced-custom-fields-acf/
*/
function new_map( $el ) {
// var
var $markers = $el.find('.marker');
// vars
var args = {
zoom : 16,
center : new google.maps.LatLng(0, 0),
mapTypeId : google.maps.MapTypeId.ROADMAP,
scrollwheel : false,
mapTypeControl: false,
streetViewControl: false,
};
// create map
var map = new google.maps.Map( $el[0], args);
// add a markers reference
map.markers = [];
// add markers
$markers.each(function(){
add_marker( $(this), map );
});
// center map
center_map( map );
/* Conditional works to find if it only has one marker, but I can't figure out what to trigger */
//console.log($markers);
if($markers.length == 1) {
console.log('yes');
}
}
var infowindow = new google.maps.InfoWindow({
content : ''
});
/*
* add_marker
*
* This function will add a marker to the selected Google Map
*
* #type function
* #date 8/11/2013
* #since 4.3.0
*
* #param $marker (jQuery element)
* #param map (Google Map object)
* #return n/a
*/
function add_marker( $marker, map ) {
// var
var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );
// create marker
var marker = new google.maps.Marker({
position : latlng,
map : map,
open : true
});
// add to array
map.markers.push( marker );
// if marker contains HTML, add it to an infoWindow
if( $marker.html() ) {
// show info window when marker is clicked & close other markers
google.maps.event.addListener(marker, 'click', function() {
//swap content of that singular infowindow
infowindow.setContent($marker.html());
infowindow.open(map, marker);
});
// close info window when map is clicked
google.maps.event.addListener(map, 'click', function(event) {
if (infowindow) {
infowindow.close();
}
});
}
}
/*
* center_map
*
* This function will center the map, showing all markers attached to this map
*
* #type function
* #date 8/11/2013
* #since 4.3.0
*
* #param map (Google Map object)
* #return n/a
*/
function center_map( map ) {
// vars
var bounds = new google.maps.LatLngBounds();
// loop through all markers and create bounds
$.each( map.markers, function( i, marker ){
var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
bounds.extend( latlng );
});
// only 1 marker?
if( map.markers.length == 1 ) {
// set center of map
map.setCenter( bounds.getCenter() );
map.setZoom( 10 );
}
else {
// fit to bounds
map.fitBounds( bounds );
}
}
/* This function will render each map when the document is ready (page has loaded)
*
* #type function
* #date 8/11/2013
* #since 5.0.0
*
* #param n/a
* #return n/a
*/
// global var
var map = null;
$(document).ready(function(){
$('.acf-map').each(function(){
// create map
map = new_map( $(this) );
});
});
})(jQuery);
</script>

In the new_map function you can check the length of the array before adding the markers. if the length is 1 then pass a parameter indicating that showInfoWindow is true, else false.
var showInfoWindow = false;
if($markers.length == 1) {
showInfoWindow = true
}
// add markers
$markers.each(function(){
add_marker( $(this), map , showInfoWindow);
});
And then modify the add_marker code as follows
function add_marker( $marker, map, showInfoWindow ) {
// var
var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );
// create marker
var marker = new google.maps.Marker({
position : latlng,
map : map,
open : true
});
// add to array
map.markers.push( marker );
// if marker contains HTML, add it to an infoWindow
if( $marker.html() ) {
// show info window when marker is clicked & close other markers
google.maps.event.addListener(marker, 'click', function() {
//swap content of that singular infowindow
infowindow.setContent($marker.html());
infowindow.open(map, marker);
});
// close info window when map is clicked
google.maps.event.addListener(map, 'click', function(event) {
if (infowindow) {
infowindow.close();
}
});
if(showInfoWindow)
{
infowindow.setContent($marker.html());
infowindow.open(map, marker);
}
}
}

Related

how to put searchBox inside gmaps?

i have problem.. i have canvas gmaps and i added some input-text for searching mark on gmaps canvas. The problem is this "input-text for searching" located outside the gmaps canvas, how to move "input-text for searching" inside the gmaps canvas?
here is the HTML and maps.JS
HTML :
<div class="form-group ">
<input id="map-search" class="controls" type="text" placeholder="Search Box" size="50%" >
<div id="map-canvas"></div>
</div>
JavaScript :
function initialize() {
var mapOptions, map, marker, searchBox, city,
infoWindow = '',
addressEl = document.querySelector( '#map-search' ),
latEl = document.querySelector( '.latitude' ),
longEl = document.querySelector( '.longitude' ),
element = document.getElementById( 'map-canvas' );
city = document.querySelector( '.reg-input-city' );
if($('#latspan' ).val() == null){
var latCar = -6.175350;
} else {
var latCar = $('#latspan').val();
}
if($('#lngspan').val() == null){
var longCar = 106.827164;
} else {
var longCar = $('#lngspan').val();
}
mapOptions = {
// How far the maps zooms in.
zoom: 800,
// Current Lat and Long position of the pin/
center: new google.maps.LatLng( latCar, longCar ),
// center : {
// lat: -34.397,
// lng: 150.644
// },
disableDefaultUI: false, // Disables the controls like zoom control on the map if set to true
scrollWheel: true, // If set to false disables the scrolling on the map.
draggable: true, // If set to false , you cannot move the map around.
// mapTypeId: google.maps.MapTypeId.HYBRID, // If set to HYBRID its between sat and ROADMAP, Can be set to SATELLITE as well.
// maxZoom: 11, // Wont allow you to zoom more than this
// minZoom: 9 // Wont allow you to go more up.
};
/**
* Creates the map using google function google.maps.Map() by passing the id of canvas and
* mapOptions object that we just created above as its parameters.
*
*/
// Create an object map with the constructor function Map()
map = new google.maps.Map( element, mapOptions ); // Till this like of code it loads up the map.
/**
* Creates the marker on the map
*
*/
marker = new google.maps.Marker({
position: mapOptions.center,
map: map,
// icon: 'http://pngimages.net/sites/default/files/google-maps-png-image-70164.png',
draggable: true,
animation: google.maps.Animation.DROP
});
/**
* Creates a search box
*/
searchBox = new google.maps.places.SearchBox( addressEl );
/**
* When the place is changed on search box, it takes the marker to the searched location.
*/
google.maps.event.addListener( searchBox, 'places_changed', function () {
var places = searchBox.getPlaces(),
bounds = new google.maps.LatLngBounds(),
i, place, lat, long, resultArray,
addresss = places[0].formatted_address;
for( i = 0; place = places[i]; i++ ) {
bounds.extend( place.geometry.location );
marker.setPosition( place.geometry.location ); // Set marker position new.
}
map.fitBounds( bounds ); // Fit to the bound
map.setZoom( 15 ); // This function sets the zoom to 15, meaning zooms to level 15.
// console.log( map.getZoom() );
lat = marker.getPosition().lat();
long = marker.getPosition().lng();
latEl.value = lat;
longEl.value = long;
resultArray = places[0].address_components;
// Get the city and set the city input value to the one selected
for( var i = 0; i < resultArray.length; i++ ) {
if ( resultArray[ i ].types[0] && 'administrative_area_level_2' === resultArray[ i ].types[0] ) {
citi = resultArray[ i ].long_name;
city.value = citi;
}
}
// Closes the previous info window if it already exists
if ( infoWindow ) {
infoWindow.close();
}
/**
* Creates the info Window at the top of the marker
*/
infoWindow = new google.maps.InfoWindow({
content: addresss
});
infoWindow.open( map, marker );
} );
/**
* Finds the new position of the marker when the marker is dragged.
*/
google.maps.event.addListener( marker, "dragend", function ( event ) {
var lat, long, address, resultArray, citi;
console.log( 'i am dragged' );
lat = marker.getPosition().lat();
long = marker.getPosition().lng();
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { latLng: marker.getPosition() }, function ( result, status ) {
if ( 'OK' === status ) { // This line can also be written like if ( status == google.maps.GeocoderStatus.OK ) {
address = result[0].formatted_address;
resultArray = result[0].address_components;
// Get the city and set the city input value to the one selected
// for( var i = 0; i < resultArray.length; i++ ) {
// if ( resultArray[ i ].types[0] && 'administrative_area_level_2' === resultArray[ i ].types[0] ) {
// citi = resultArray[ i ].long_name;
// console.log( citi );
// city.value = citi;
// }
// }
//addressEl.value = address;
latEl.value = lat;
longEl.value = long;
} else {
console.log( 'Geocode was not successful for the following reason: ' + status );
}
// Closes the previous info window if it already exists
if ( infoWindow ) {
infoWindow.close();
}
/**
* Creates the info Window at the top of the marker
*/
infoWindow = new google.maps.InfoWindow({
content: address
});
infoWindow.open( map, marker );
} );
});
}
Here is the picture on my gmaps canvas pict
thank you for being willing to read this thread, please help
Use map.controls with correct position values
var searchBox = new google.maps.places.SearchBox(document.getElementById('map-search'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('map-search'));

Only show one map location window at a time

I'm using this script to show small info windows next to each respective map location, using the Google maps API.
The problem is as you click Location 01, Location 02 etc the small windows remain open and can easily appear over top of each other, which isn't very user friendly.
What I need to do is have it so that only one of the small info windows can be visible at any given time. So for example, if I click 'Location 01' then all other info windows that might have been open will close.
You can see the fiddle in action here: https://jsfiddle.net/vm4cksue/
...or view my code here...
(function($) {
function new_map( $el ) {
// var
var $markers = $el.find('.marker');
// vars
var args = {
//zoom : 14,
center : new google.maps.LatLng(0, 0),
scrollwheel : false,
mapTypeId : google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
}
};
// create map
var map = new google.maps.Map( $el[0], args);
// add a markers reference
map.markers = [];
// add markers
// add identifying number to each marker
var sidebar = 1;
$markers.each(function(){
add_marker( $(this), map, sidebar);
sidebar++;
});
// center map
center_map( map );
// return
return map;
}
function add_marker( $marker, map, sidebar ) {
// dynamic Lat & Long
var latlng = new google.maps.LatLng(
$marker.attr('data-lat'), $marker.attr('data-lng')
);
// Dynamic marker
var icon = $marker.attr('data-icon');
// create marker
var marker = new google.maps.Marker({
position: latlng,
map: map,
animation: google.maps.Animation.DROP, // animation
icon: icon,
});
// add to array
map.markers.push( marker );
// if marker contains HTML, add it to an infoWindow
if( $marker.html() )
{
// create info window
var infowindow = new google.maps.InfoWindow({
content : '<div id="iw-container">' + $marker.html() + '</div>'
});
/*
* The google.maps.event.addListener() event waits for
* the creation of the infowindow HTML structure 'domready'
* and before the opening of the infowindow defined styles
* are applied.
*/
google.maps.event.addListener(infowindow, 'domready', function() {
// Reference to the DIV which receives the contents of the infowindow using jQuery
var iwOuter = $('.gm-style-iw');
// Restyle parent DIVs
var iwBackground = iwOuter.prev();
// Removes background shadow DIV
iwBackground.children(':nth-child(2)').css({'display' : 'none'});
// Removes white background DIV
iwBackground.children(':nth-child(4)').css({'display' : 'none'});
// Moves the infowindow 115px to the right.
iwOuter.parent().parent().css({left: '125px'});
// Moves the shadow of the arrow 76px to the left margin.
iwBackground.children(':nth-child(1)').attr('style', function(i,s){ return s + 'left: 26px !important;'});
// Moves the arrow 76px to the left margin.
iwBackground.children(':nth-child(3)').attr('style', function(i,s){ return s + 'left: 26px !important;'});
// Changes the desired tail shadow color.
iwBackground.children(':nth-child(3)').find('div').children().css({'box-shadow': 'rgba(72, 181, 233, 0.6) 0px 1px 6px', 'z-index' : '1'});
// Restyle child DIVs
var iwBackground = iwOuter.next();
// Set a new variable iwCloseBtn.
var iwCloseBtn = iwOuter.next();
// hide default Google Maps sprite on close tag
iwCloseBtn.children(':nth-child(1)').css({'display' : 'none'});
// Apply the desired effect to the close button
iwCloseBtn.css({
width: '45px',
height: '45px',
opacity: '1', // by default the close button has an opacity of 0.7
right: '0',
top: '0', // button repositioning
'background-image':'url(https://cdn0.iconfinder.com/data/icons/very-basic-android-l-lollipop-icon-pack/24/close-32.png)', // adding background image
'background-size': '25px',
'background-position': 'center',
'background-repeat': 'no-repeat'
});
// The API automatically applies 0.7 opacity to the button after the mouseout event.
// This function reverses this event to the desired value.
iwCloseBtn.mouseout(function(){
$(this).css({opacity: '1'});
});
});
// Create a click on the sidebar list and open the info window
$('#m'+sidebar).click(function(){
// Close info windows
$.each(map.markers, function(index,value){
if(infowindow)
infowindow.close();
});
// Click on the marker
google.maps.event.trigger(marker, "click");
});
// show info window when marker is clicked
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
function center_map( map ) {
// vars
var bounds = new google.maps.LatLngBounds();
// loop through all markers and create bounds
$.each( map.markers, function( i, marker ){
var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
bounds.extend( latlng );
});
// only 1 marker?
if( map.markers.length == 1 )
{
// set center of map
map.setCenter( bounds.getCenter() );
//map.setZoom( 14 );
}
else
{
// fit to bounds
//map.fitBounds( bounds );
map.setCenter( bounds.getCenter() );
map.setZoom( 7 );
}
}
var map = null;
$(document).ready(function(){
$('.acf-map').each(function(){
// create map
map = new_map( $(this) );
});
});
})(jQuery);
You could declare a window level var actOpenWindow for store the actual open window and close before open a new one
var actInfoWindow = null;
then in your listener you shoul manage the proper situation
google.maps.event.addListener(marker, 'click', function() {
if (actInfoWindow){
actInfoWindow.close();
}
if (infowindow!==actInfoWindow){
infowindow.open( map, marker );
actInfoWindow = infowindow;
} else {
actInfoWindow.close();
actInfoWindow = null;
}
});
see https://jsfiddle.net/j10axkhc/5/ for test

Google Maps v3 API and WordPress ACF: Multiple Custom Markers

I’ve found lots of code for how to add custom markers to Google Maps, but hardly anything about using different markers on the same map. For instance, I may have 4 markers from an Advanced Custom Fields repeater field that I want to appear with a green marker, and the rest of the markers related to a custom post type to appear with a gray marker.
I’ve tried a few different methods, like duplicating the marker variable and changing the name and colors, but everything I try breaks some part of the map.
Here's a screenshot of the two different types of map markers I need: http://screencast.com/t/Cc5eE7St
The code below works, but it's all one type of marker.
<style type="text/css">
.acf-map {
width: 100%;
height: 730px;
}
/* fixes potential theme css conflict */
.acf-map img {
max-width: inherit !important;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
(function($) {
/*
* new_map
*
* This function will render a Google Map onto the selected jQuery element
*
* #type function
* #date 8/11/2013
* #since 4.3.0
*
* #param $el (jQuery element)
* #return n/a
*/
function new_map( $el ) {
// var
var $markers = $el.find('.marker');
// vars
var args = {
zoom : 5,
scrollwheel: false,
center: {lat: 39.8, lng: 98.5795},
mapTypeId : google.maps.MapTypeId.ROADMAP,
styles: [
{
"featureType": "all",
"elementType": "all"
};
// create map
var map = new google.maps.Map( $el[0], args);
// add a markers reference
map.markers = [];
// add markers
$markers.each(function(){
add_marker( $(this), map );
});
// center map
center_map( map );
// return
return map;
}
/*
* add_marker
*
* This function will add a marker to the selected Google Map
*
* #type function
* #date 8/11/2013
* #since 4.3.0
*
* #param $marker (jQuery element)
* #param map (Google Map object)
* #return n/a
*/
function add_marker( $marker, map ) {
// var
var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );
// // create marker
// var marker = new google.maps.Marker({
// position : latlng,
// map : map
// });
var grayCircle = {
//path: 'M -1,0 A 1,1 0 0 0 1,0 1,1 0 0 0 -1,0 z',
path: google.maps.SymbolPath.CIRCLE,
fillColor: '#888888',
fillOpacity: 1,
scale: 3,
strokeColor: "#888888",
strokeWeight: 3
};
var marker = new google.maps.Marker({
position: latlng,
icon: grayCircle,
map: map
});
// add to array
map.markers.push( marker );
// if marker contains HTML, add it to an infoWindow
if( $marker.html() )
{
// create info window
var infowindow = new google.maps.InfoWindow({
content : $marker.html()
});
// show info window when marker is clicked
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
/*
* center_map
*
* This function will center the map, showing all markers attached to this map
*
* #type function
* #date 8/11/2013
* #since 4.3.0
*
* #param map (Google Map object)
* #return n/a
*/
function center_map( map ) {
// vars
var bounds = new google.maps.LatLngBounds();
// loop through all markers and create bounds
$.each( map.markers, function( i, marker ){
var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
bounds.extend( latlng );
});
// only 1 marker?
if( map.markers.length == 1 )
{
// set center of map
map.setCenter( bounds.getCenter() );
map.setZoom( 5 );
}
else
{
// fit to bounds
map.fitBounds( bounds );
}
}
/*
* document ready
*
* This function will render each map when the document is ready (page has loaded)
*
* #type function
* #date 8/11/2013
* #since 5.0.0
*
* #param n/a
* #return n/a
*/
// global var
var map = null;
$(document).ready(function(){
$('.acf-map').each(function(){
// create map
map = new_map( $(this) );
});
});
})(jQuery);
</script>
<div class="portfolio-map">
<div class="acf-map">
<?php
// check if the repeater field has rows of data
if( have_rows('site_details') ):
// loop through the rows of data
while ( have_rows('site_details') ) : the_row();
// display a sub field value
$siteName = get_sub_field('site_name');
$siteLink = get_sub_field('site_link');
$siteAddress = get_sub_field('site_address');
?>
<!-- I would like this set of information to have a green marker --> <div class="marker" data-lat="<?php echo $siteAddress['lat']; ?>" data-lng="<?php echo $siteAddress['lng']; ?>">
<h4><?php echo $siteName; ?></h4>
</div>
<?php
endwhile;
else :
// no rows found
endif;
?>
<?
$args = array(
'post_type' => 'organization',
'posts_per_page' => 99
);
$locationMap = new WP_Query($args);
$count = 0;
?>
<? if($locationMap->have_posts()) : while($locationMap->have_posts()) : $locationMap->the_post();
$count++;
$location = get_field('organization_address');
$siteLocation = get_field('site_address');
?>
<!-- I would like this set of information to have a gray marker --> <div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">
<a href="<?php the_permalink(); ?>">
<img class="popup" src="<?php the_field('logo'); ?>"/>
</a>
<div class="popup-details">
<?php the_field('map_popup_details'); ?>
</div>
<div class="popup-link">
Learn More
</div>
</div>
<? endwhile; endif; ?>
<?php wp_reset_query(); ?>
</div>
</div>
Charlotte, you could add a "data-marker" attribute to each of your marker objects as you build the markup, like this (green/grey wherever you need them)
<div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; data-marker="green/grey" ?>">
And then in the javascript you can check the marker type using the data-marker you set in the code, like this
var grayCircle = {
//path: 'M -1,0 A 1,1 0 0 0 1,0 1,1 0 0 0 -1,0 z',
path: google.maps.SymbolPath.CIRCLE,
fillColor: '#888888',
fillOpacity: 1,
scale: 3,
strokeColor: "#888888",
strokeWeight: 3
};
var greenMarker = //create your marker here
//Check your marker type, if it's green then set that otherwise leave it grey
var markerType = $marker.attr('data-marker')=="green"?greenMarker:greyCircle;
var marker = new google.maps.Marker({
position: latlng,
//Set your marker using markerType here
icon: markerType,
map: map
});

Implementing Google Maps Spiderfier

I'm trying to implement https://github.com/jawj/OverlappingMarkerSpiderfier to handle multiple map markers that can occur in the exact same location. I'm using the below javascript to grab the map data from divs of class .marker and create the map. It's functioning and works great.
function initialize() {
function render_map( $el ) {
// var
var $markers = $el.find('.marker');
// vars
var args = {
zoom : 8,
center : new google.maps.LatLng(42.7086815, -84.559032),
scrollwheel : false,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// create map
var map = new google.maps.Map( $el[0], args);
// add a markers reference
map.markers = [];
// add markers
$markers.each(function(){
add_marker( $(this), map );
});
var padder = document.createElement('div');
padder.style.height = '100px';
padder.style.width = '100%';
map.controls[google.maps.ControlPosition.TOP_CENTER].push(padder);
// center map
center_map( map );
}
function add_marker( $marker, map ) {
// var
var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );
// create marker
var marker = new google.maps.Marker({
position : latlng,
map : map
});
// add to array
map.markers.push( marker );
// if marker contains HTML, add it to an infoWindow
if( $marker.html() )
{
// create info window
var infowindow = new google.maps.InfoWindow({
content : $marker.html()
});
// show info window when marker is clicked
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
map.setCenter(marker.getPosition());
});
}
}
function center_map( map ) {
// vars
var bounds = new google.maps.LatLngBounds();
// loop through all markers and create bounds
$.each( map.markers, function( i, marker ){
var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
bounds.extend( latlng );
});
// only 1 marker?
if( map.markers.length == 1 )
{
// set center of map
map.setCenter( bounds.getCenter() );
}
else if( map.markers.length == 0 )
{
// set center of map
map.setCenter( 42.7086815, -84.559032 );
}
else
{
// fit to bounds
map.fitBounds( bounds );
}
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom() > 8) {
this.setZoom(8);
}
});
}
$(document).ready(function(){
$('#acf-map').each(function(){
render_map( $(this) );
});
});
}
However, when I try to integrate what I have with Spiderfier js, the map markers are not showing up. This is my sorry attempt at merging the js. Any idea of how I can use Spiderfier but still grab the content from the .marker divs?
function initialize() {
function render_map( $el ) {
// var
var $markers = $el.find('.marker');
// vars
var args = {
zoom : 8,
center : new google.maps.LatLng(42.7086815, -84.559032),
scrollwheel : false,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// create map
var map = new google.maps.Map( $el[0], args);
var oms = new OverlappingMarkerSpiderfier(map);
var iw = new google.maps.InfoWindow();
oms.addListener('click', function(marker, event) {
iw.setContent(marker.desc);
iw.open(map, marker);
});
oms.addListener('spiderfy', function(markers) {
iw.close();
});
// var
var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );
// create marker
var marker = new google.maps.Marker({
position : latlng,
map : map
});
marker.desc = $marker.html();
oms.addMarker(marker);
var padder = document.createElement('div');
padder.style.height = '100px';
padder.style.width = '100%';
map.controls[google.maps.ControlPosition.TOP_CENTER].push(padder);
// center map
center_map( map );
}
function center_map( map ) {
// vars
var bounds = new google.maps.LatLngBounds();
// loop through all markers and create bounds
$.each( map.markers, function( i, marker ){
var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
bounds.extend( latlng );
});
// only 1 marker?
if( map.markers.length == 1 )
{
// set center of map
map.setCenter( bounds.getCenter() );
}
else if( map.markers.length == 0 )
{
// set center of map
map.setCenter( 42.7086815, -84.559032 );
}
else
{
// fit to bounds
map.fitBounds( bounds );
}
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom() > 8) {
this.setZoom(8);
}
});
}
$(document).ready(function(){
$('#acf-map').each(function(){
render_map( $(this) );
});
});
}
Below is the correctly integrated javascript in case it's helpful to anyone else.
function initialize() {
/*
* render_map
*
* This function will render a Google Map onto the selected jQuery element
*
* #type function
* #date 8/11/2013
* #since 4.3.0
*
* #param $el (jQuery element)
* #return n/a
*/
function render_map( $el ) {
// var
var $markers = $el.find('.marker');
// vars
var args = {
zoom : 8,
center : new google.maps.LatLng(42.7086815, -84.559032),
scrollwheel : false,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// create map
var map = new google.maps.Map( $el[0], args);
var oms = new OverlappingMarkerSpiderfier(map);
var iw = new google.maps.InfoWindow();
oms.addListener('click', function(marker, event) {
iw.setContent(marker.desc);
iw.open(map, marker);
});
oms.addListener('spiderfy', function(markers) {
iw.close();
});
$markers.each(function(index, item) {
// create latlng
var latlng = new google.maps.LatLng( $(item).attr('data-lat'), $(item).attr('data-lng') );
// create marker
var iconBase = '/images/';
var marker = new google.maps.Marker({
position : latlng,
map : map,
icon: iconBase + 'marker.png'
});
marker.desc = $(item).html();
oms.addMarker(marker);
});
var padder = document.createElement('div');
padder.style.height = '100px';
padder.style.width = '100%';
map.controls[google.maps.ControlPosition.TOP_CENTER].push(padder);
// center map
center_map(map);
}
/*
* center_map
*
* This function will center the map, showing all markers attached to this map
*
* #type function
* #date 8/11/2013
* #since 4.3.0
*
* #param map (Google Map object)
* #return n/a
*/
function center_map(map) {
// vars
var bounds = new google.maps.LatLngBounds();
// loop through all markers and create bounds
$.each( map.markers, function( i, marker ){
var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
bounds.extend( latlng );
});
// only 1 marker?
if( map.markers.length == 1 )
{
// set center of map
map.setCenter( bounds.getCenter() );
}
else if( map.markers.length == 0 )
{
// set center of map
map.setCenter( 42.7086815, -84.559032 );
}
else
{
// fit to bounds
map.fitBounds( bounds );
}
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom() > 8) {
this.setZoom(8);
}
});
}
/*
* document ready
*
* This function will render each map when the document is ready (page has loaded)
*
* #type function
* #date 8/11/2013
* #since 5.0.0
*
* #param n/a
* #return n/a
*/
$(document).ready(function(){
$('#acf-map').each(function(){
render_map( $(this) );
});
});
}

Google Maps v3 Centering and Infowindow control

I have a map that has checkboxes for users to select what they would like displayed on the map. Everything works well with the exception of the following two items.
When a user selects an item from the list the marker does display on the map, however the map does not re-center on the marker. This is needed for a marker that is outside the viewable area of the map when the page loads.
When I have multiple markers open on the map I would like to have only 1 infowindow open at a time, currently if I click on 10 markers there will be 10 infowindows open. I would like to have it where if an infowindow is open and another marker is clicked then the first infowindow closes.
I have pasted a snippet of the code for one of the markers below, any help would be greatly appreciated!
jQuery(document).ready(function(){
/**
* The Map object.
* #type {google.maps.Map}
*/
var mapOptions = {
center: new google.maps.LatLng(36.812946,-119.746953),
zoom: 16,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
/**
* The markers array.
* #type {Object}
*/
var markers = {};
markers.building37 = [];
var marker0237 = new google.maps.Marker({
visible: false,
icon: new google.maps.MarkerImage("images/website/brown_Marker.png",new google.maps.Size(32,37),null,null),
title: 'Building',
position: new google.maps.LatLng(36.80694607313768,-119.73590791225433),
center: position,
map: map
});
markers.building37.push(marker0237);
var info_window0237 = new google.maps.InfoWindow({
content: '<div id="infobubble"><div id="img"><img src="images/buildings/Foundation001.jpg" alt="Foundation Building"></div><div id="desc"><h3>Foundation</h3></div></div>',
maxWidth:350,
});
google.maps.event.addListener(marker0237, "click", function() {
info_window0237.open(map,marker0237);
});
var showBuilding37 = false;
var mgrBuilding37 = null;
/**
* Toggles Building 37 Marker Group visibility.
*/
function toggleBuilding37()
{
showBuilding37 = !showBuilding37;
if (showBuilding37)
for (var i=0; i < markers.building37.length; i++)
markers.building37[i].setVisible(true);
if (mgrBuilding37)
{
if (showBuilding37)
{
mgrBuilding37.addMarkers(markers.building37, 0);
mgrBuilding37.refresh();
}
else
{
mgrBuilding37.clearMarkers();
mgrBuilding37.refresh();
}
}
else
{
mgrBuilding37 = new MarkerManager(map, {trackMarkers: true, maxZoom: 15});
google.maps.event.addListener(mgrBuilding37, "loaded", function() {
if (showBuilding37)
{
mgrBuilding37.addMarkers(markers.building37, 0);
mgrBuilding37.refresh();
}
else
{
mgrBuilding37.clearMarkers();
mgrBuilding37.refresh();
}
});
}
}
google.maps.event.addDomListener(
document.getElementById("building37-cb"),"click", toggleBuilding37);
});
I don't see where you are setting the map center.
You should do something like map.setCenter(location); when you add a marker.
You should keep a list of info windows and when you display one, loop through the others and hide their info windows.
//Declare your info window array
var infoWindows = new Array();
var info_window0237 = new google.maps.InfoWindow({
content: '<div id="infobubble"><div id="img"><img src="images/buildings/Foundation001.jpg" alt="Foundation Building"></div><div id="desc"><h3>Foundation</h3></div></div>',
maxWidth:350,
});
//After you make an infowindow, add it to the array
infoWindows.push(info_window0237);
google.maps.event.addListener(marker0237, "click", function() {
//When you show an infowindow on click, hide the rest
for(i = 0; i < indowWindows.length; i++)
{
//this will close all the infowindows you added to the array
infoWindows[i].close();
}
info_window0237.open(map,marker0237);
});

Categories

Resources