Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /************ FUNCTIONS.JS ************************/
- /*************************************************/
- /**
- * @package BasicGoogleMapsPlacemarks
- * @author Ian Dunn <ian@iandunn.name>
- * @link http://wordpress.org/extend/plugins/basic-google-maps-placemarks/
- */
- /**
- * Wrapper function to safely use $
- * @author Ian Dunn <ian@iandunn.name>
- */
- function bgmp_wrapper( $ )
- {
- // @todo - figure out if wrapper bad for memory consumption (https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Efficiency_considerations)
- // ask on stackoverflow
- $.bgmp =
- {
- /**
- * Main entry point
- * @author Ian Dunn <ian@iandunn.name>
- */
- init : function()
- {
- $.bgmp.name = 'Basic Google Maps Placemarks';
- $.bgmp.canvas = document.getElementById( 'bgmp_map-canvas' ); // We have to use getElementById instead of a jQuery selector here in order to pass it to the Maps API.
- $.bgmp.previousInfoWindow = undefined;
- $.bgmp.map = undefined;
- $.bgmp.markerClusterer = undefined;
- $.bgmp.markers = [];
- //custom stuff for Filters Jesse 13/Dec
- $.bgmp.markers.all = [];
- // @todo make this loop through array instead of manual. also add any other numbers
- bgmpData.options.zoom = parseInt( bgmpData.options.zoom ),
- bgmpData.options.latitude = parseFloat( bgmpData.options.latitude );
- bgmpData.options.longitude = parseFloat( bgmpData.options.longitude );
- bgmpData.options.clustering.maxZoom = parseInt( bgmpData.options.clustering.maxZoom );
- bgmpData.options.clustering.gridSize = parseInt( bgmpData.options.clustering.gridSize );
- if( $.bgmp.canvas ) {
- $.bgmp.buildMap();
- }
- else
- $( $.bgmp.canvas ).html( $.bgmp.name + " error: couldn't retrieve DOM elements." );
- },
- /**
- * Pull in the map options from Wordpress' database and create the map
- * @author Ian Dunn <ian@iandunn.name>
- */
- buildMap : function()
- {
- var mapOptions;
- if( bgmpData.options.mapWidth == '' || bgmpData.options.mapHeight == '' || bgmpData.options.latitude == '' || bgmpData.options.longitude == '' || bgmpData.options.zoom == '' || bgmpData.options.infoWindowMaxWidth == '' )
- {
- // @todo update w/ cluster options?
- $( $.bgmp.canvas ).html( $.bgmp.name + " error: map options not set." );
- return;
- }
- mapOptions =
- {
- 'zoom' : 15,//not working.bgmpData.options.zoom,
- 'center' : new google.maps.LatLng( bgmpData.options.latitude, bgmpData.options.longitude ),
- 'mapTypeId' : google.maps.MapTypeId[ bgmpData.options.type ],
- 'mapTypeControl' : bgmpData.options.typeControl == 'off' ? false : true,
- 'mapTypeControlOptions' : { style: google.maps.MapTypeControlStyle[ bgmpData.options.typeControl ] },
- 'navigationControl' : bgmpData.options.navigationControl == 'off' ? false : true,
- 'navigationControlOptions' : { style: google.maps.NavigationControlStyle[ bgmpData.options.navigationControl ] },
- 'streetViewControl' : bgmpData.options.streetViewControl
- };
- // Override default width/heights from settings
- $( '#bgmp_map-canvas' ).css( 'width', bgmpData.options.mapWidth ); //'100%'); // @todo use $.bgmp.canvas intead of hardcoding it?
- $( '#bgmp_map-canvas' ).css( 'height', bgmpData.options.mapHeight ); // '100%'); Making map responsive.
- // @todo this prevents users from using their own stylesheet?
- // Create the map
- try
- {
- $.bgmp.map = new google.maps.Map( $.bgmp.canvas, mapOptions );
- }
- catch( e )
- {
- $( $.bgmp.canvas ).html( $.bgmp.name + " error: couln't build map." );
- if( window.console )
- console.log( 'bgmp_buildMap: '+ e );
- return;
- }
- $.bgmp.addPlacemarks( $.bgmp.map ); // @todo not supposed to add them when clustering is enabled? http://www.youtube.com/watch?v=Z2VF9uKbQjI
- if( bgmpData.options.clustering.enabled )
- {
- $.bgmp.markerCluster = new MarkerClusterer( // @todo should be .markerClusterer ?
- $.bgmp.map,
- $.bgmp.markers,
- {
- maxZoom : bgmpData.options.clustering.maxZoom,
- gridSize : bgmpData.options.clustering.gridSize,
- styles : bgmpData.options.clustering.styles[ bgmpData.options.clustering.style ]
- }
- );
- }
- },
- /**
- * Checks if the value is an integer. Slightly modified version of original.
- * @author Invent Partners
- * @link http://www.inventpartners.com/content/javascript_is_int
- * @param mixed value
- * @return bool
- */
- isInt : function( value )
- {
- if( !isNaN( value ) && parseFloat( value ) == parseInt( value ) )
- return true;
- else
- return false;
- },
- /**
- * Pull the placemark posts from Wordpress' database and add them to the map
- * @author Ian Dunn <ian@iandunn.name>
- * @param object map Google Maps map
- */
- addPlacemarks : function( map )
- {
- // @todo - should probably refactor this since you pulled out the ajax. update phpdoc too
- if( bgmpData.markers.length > 0 )
- {
- for( var m in bgmpData.markers )
- {
- $.bgmp.createMarker(
- map,
- bgmpData.markers[ m ][ 'title' ],
- bgmpData.markers[ m ][ 'latitude' ],
- bgmpData.markers[ m ][ 'longitude' ],
- bgmpData.markers[ m ][ 'details' ],
- bgmpData.markers[ m ][ 'icon' ],
- parseInt( bgmpData.markers[ m ][ 'zIndex' ] ),
- bgmpData.markers[ m ][ 'categories' ], //Added by Jesse 13/Dec
- bgmpData.markers[ m ][ 'address' ] //Added by Jesse 14/Dec
- );
- }
- }
- },
- /**
- * Create a marker with an information window
- * @author Ian Dunn <ian@iandunn.name>
- * @param object map Google Maps map
- * @param string title Placemark title
- * @param float latituded
- * @param float longitude
- * @param string details Content of the infowinder
- * @param string icon URL of the icon
- * @param int zIndex The desired position in the placemark stacking order
- * @param category array <-- added by Jesse 13/Dec
- * @param string address
- * @return bool True on success, false on failure
- */
- createMarker : function( map, title, latitude, longitude, details, icon, zIndex, categories, address )
- {
- // @todo - clean up variable names
- var infowindowcontent, infowindow, marker;
- if( isNaN( latitude ) || isNaN( longitude ) )
- {
- if( window.console )
- console.log( "bgmp_createMarker(): "+ title +" latitude and longitude weren't valid." );
- return false;
- }
- if( icon == null )
- {
- // @todo - this check may not be needed anymore
- if( window.console )
- console.log( "bgmp_createMarker(): "+ title +" icon wasn't passed in." );
- return false;
- }
- if( !$.bgmp.isInt( zIndex ) )
- {
- //if( window.console )
- //console.log( "bgmp_createMarker(): "+ title +" z-index wasn't valid." ); // this would fire any time it's empty
- zIndex = 0;
- }
- infowindowcontent = '<div class="bgmp_placemark"> <h3>'+ title +'</h3> <div>'+ address + '<br />'+ details +'</div> </div>';
- try
- {
- infowindow = new google.maps.InfoWindow( {
- content : infowindowcontent,
- maxWidth : bgmpData.options.infoWindowMaxWidth
- } );
- // Replace commas with periods. Some (human) languages use commas to delimit the fraction from the whole number, but Google Maps doesn't accept that.
- latitude = parseFloat( latitude.replace( ',', '.' ) );
- longitude = parseFloat( longitude.replace( ',', '.' ) );
- marker = new google.maps.Marker( {
- 'position' : new google.maps.LatLng( latitude, longitude ),
- 'map' : map,
- 'icon' : icon,
- 'title' : title,
- 'zIndex' : zIndex
- } );
- //Store Info Window Text in an array for easy access.
- $.bgmp.markers[marker['position']] = [details, address];
- //Store Markers inside an array based on their categories. Jesse 13/Dec
- for (var s in categories) {
- title = categories[s]['name'];
- if (!$.bgmp.markers[title]){
- $.bgmp.markers[title] = [];
- $.bgmp.markers.push(title);
- }
- $.bgmp.markers[title].push(marker);
- }
- //Need to store ALL markers inside an array to compensate for the possibility of multiple categories. Jesse 13/Dec
- $.bgmp.markers.all.push( marker );
- google.maps.event.addListener( marker, 'click', function()
- {
- if( $.bgmp.previousInfoWindow != undefined )
- $.bgmp.previousInfoWindow.close();
- infowindow.open( map, marker );
- $.bgmp.previousInfoWindow = infowindow;
- $.bgmp.map.panTo(marker.getPosition());
- $.bgmp.map.setZoom(15);
- } );
- return true;
- }
- catch( e )
- {
- //$( $.bgmp.canvas ).append( '<p>' + $.bgmp.name + " error: couldn't add map placemarks.</p>"); // add class for making red? other places need this too? // @todo - need to figure out a good way to alert user that placemarks couldn't be added
- if( window.console )
- console.log( 'bgmp_createMarker: '+ e );
- }
- }
- }; // end bgmp
- // Kick things off...
- $( document ).ready( $.bgmp.init );
- } // end bgmp_wrapper()
- bgmp_wrapper( jQuery );
- /************CUSTOM JAVASCRIPT************************/
- /****************************************************/
- $.geocoder;
- var html = '';
- var stepDisplay;
- var markerArray = [];
- var bounds;
- $(document).ready(function(){
- //Add the Filtered Nav Div
- if ($('#map').length) {
- $('#map').append("<div id='filteredNav' /><hr /><div id='mapLocs' style='padding-left:30px;' />");
- $.each($.bgmp.markers, function(index, arr) {
- $('#filteredNav').append('<button class="fNav shown" value='+$.bgmp.markers[index]+''+'>'+$.bgmp.markers[index]+'</button>');
- });
- }
- //Verify that there are categories.
- if ($('#filteredNav').length > 0) {
- //This isn't a good way to do this, but this will allow the ability to show multiple groups of markers.
- $('#filteredNav button').click(function() {
- if(!$(this).hasClass('shown')) {
- $(this).addClass('shown');
- } else { $(this).removeClass('shown'); }
- hideWindows();
- hideMarkers();
- bounds = $.bgmp.map.getBounds();
- //show only the markers that should be visible
- showMarkers();
- });
- //Center Map on Marker Clicked
- $('#mapLocs').on('click','a', function(event) {
- event.preventDefault();
- var loc = $(this).attr('class').split('-');
- $.bgmp.map.panTo($.bgmp.markers[loc[0]][loc[1]].getPosition());
- $.bgmp.map.setZoom(15);
- });
- }
- //Override Search
- $('form[id=mapSearchForm]').submit(function(e) {
- e.preventDefault();
- codeAddress($(this).find('input[name="q"]').val());
- });
- //http://stackoverflow.com/questions/4338490/google-map-event-bounds-changed-triggered-multiple-times-when-dragging
- //https://developers.google.com/maps/documentation/javascript/events#EventListeners
- google.maps.event.addListener($.bgmp.map, 'bounds_changed', function () {
- bounds = $.bgmp.map.getBounds();
- window.setTimeout(function() {
- //hideWindows();
- html = "";
- //window.alert('Timer Fired');
- showMarkers();
- }, 300);
- });
- initialize();
- });
- //Hide info window
- function hideWindows() {
- if( $.bgmp.previousInfoWindow != undefined )
- $.bgmp.previousInfoWindow.close();
- }
- //Hide all markers
- function hideMarkers() {
- $.each($.bgmp.markers.all, function(index, marker) {
- $.each(marker, function(key, value) {
- marker.setVisible(false);
- });
- });
- }
- //Show Markers
- function showMarkers() {
- html="";
- $('#filteredNav .shown').each(function() {
- var check = $(this).attr('value');
- html = html + '<h3>'+check+'</h3><ul>';
- $.each($.bgmp.markers[check], function(index, marker) {
- $.each(marker, function(key, value) {
- marker.setVisible(true);
- //html = html+'key: '+key+' = value: '+value+';<br /> ';
- });
- if(bounds.contains(marker.getPosition())) {
- html = html +'<li style="list-style:none;"><a style="cursor:pointer;" class="'+check+'-'+index+'"><img style="float:left;" src="'+marker.getIcon()+'" /> ';
- html = html +marker.getTitle()+'</a> '+$.bgmp.markers[marker['position']][1]+'<div class="markDesc">'+$.bgmp.markers[marker['position']][0]+'</div></li>';
- }
- });
- html = html+'</ul>';
- });
- $('#mapLocs').html(html);
- }
- //Credit to: http://stackoverflow.com/questions/6140303/google-maps-v3-how-to-center-using-an-address-on-initialize
- function codeAddress(address) {
- $.geocoder = new google.maps.Geocoder();
- $.geocoder.geocode( { 'address': address}, function(results, status) {
- if (status == google.maps.GeocoderStatus.OK) {
- $.bgmp.map.panTo(results[0].geometry.location);
- }
- });
- }
- //Google Maps Directions Information
- //https://developers.google.com/maps/documentation/javascript/directions
- var directionsDisplay;
- var directionsService = new google.maps.DirectionsService();
- function initialize() {
- directionsDisplay = new google.maps.DirectionsRenderer();
- directionsDisplay.setMap($.bgmp.map);
- directionsDisplay.setPanel(document.getElementById('directionsPanel'));
- stepDisplay = new google.maps.InfoWindow();
- }
- $('form[id=directionsForm]').submit(function(e) {
- e.preventDefault();
- calcRoute();
- });
- function calcRoute() {
- var start = document.getElementById("start").value;
- var end = document.getElementById("end").value;
- var request = {
- origin:start,
- destination:end,
- travelMode: google.maps.TravelMode.DRIVING
- };
- directionsService.route(request, function(result, status) {
- if (status == google.maps.DirectionsStatus.OK) {
- directionsDisplay.setDirections(result);
- showSteps(result);
- }
- });
- }
- function showSteps(directionResult) {
- // For each step, place a marker, and add the text to the marker's
- // info window. Also attach the marker to an array so we
- // can keep track of it and remove it when calculating new
- // routes.
- var myRoute = directionResult.routes[0].legs[0];
- for (var i = 0; i < myRoute.steps.length; i++) {
- var marker = new google.maps.Marker({
- position: myRoute.steps[i].start_point,
- map: $.bgmp.map
- });
- attachInstructionText(marker, myRoute.steps[i].instructions);
- markerArray[i] = marker;
- }
- }
- function attachInstructionText(marker, text) {
- google.maps.event.addListener(marker, 'click', function() {
- // Open an info window when the marker is clicked on,
- // containing the text of the step.
- stepDisplay.setContent(text);
- stepDisplay.open($.bgmp.map, marker);
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement