Advertisement
Guest User

Untitled

a guest
Dec 14th, 2012
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /************ FUNCTIONS.JS ************************/
  2. /*************************************************/
  3. /**
  4.  * @package BasicGoogleMapsPlacemarks
  5.  * @author Ian Dunn <ian@iandunn.name>
  6.  * @link http://wordpress.org/extend/plugins/basic-google-maps-placemarks/
  7.  */
  8.  
  9.  
  10. /**
  11.  * Wrapper function to safely use $
  12.  * @author Ian Dunn <ian@iandunn.name>
  13.  */
  14. function bgmp_wrapper( $ )
  15. {
  16.     // @todo - figure out if wrapper bad for memory consumption (https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Efficiency_considerations)
  17.         // ask on stackoverflow
  18.    
  19.     $.bgmp =
  20.     {
  21.         /**
  22.          * Main entry point
  23.          * @author Ian Dunn <ian@iandunn.name>
  24.          */
  25.         init : function()
  26.         {
  27.             $.bgmp.name                 = 'Basic Google Maps Placemarks';
  28.             $.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.
  29.             $.bgmp.previousInfoWindow   = undefined;
  30.             $.bgmp.map                  = undefined;
  31.             $.bgmp.markerClusterer      = undefined;
  32.             $.bgmp.markers              = [];
  33.            
  34.            
  35.             //custom stuff for Filters Jesse 13/Dec
  36.             $.bgmp.markers.all = [];
  37.  
  38.            
  39.             // @todo make this loop through array instead of manual. also add any other numbers
  40.             bgmpData.options.zoom                   = parseInt( bgmpData.options.zoom ),
  41.             bgmpData.options.latitude               = parseFloat( bgmpData.options.latitude );
  42.             bgmpData.options.longitude              = parseFloat( bgmpData.options.longitude );
  43.             bgmpData.options.clustering.maxZoom     = parseInt( bgmpData.options.clustering.maxZoom );
  44.             bgmpData.options.clustering.gridSize    = parseInt( bgmpData.options.clustering.gridSize );
  45.                                
  46.             if( $.bgmp.canvas ) {
  47.                 $.bgmp.buildMap();
  48.             }
  49.             else
  50.                 $( $.bgmp.canvas ).html( $.bgmp.name + " error: couldn't retrieve DOM elements." );
  51.         },
  52.        
  53.         /**
  54.          * Pull in the map options from Wordpress' database and create the map
  55.          * @author Ian Dunn <ian@iandunn.name>
  56.          */
  57.         buildMap : function()
  58.         {
  59.             var mapOptions;
  60.            
  61.             if( bgmpData.options.mapWidth == '' || bgmpData.options.mapHeight == '' || bgmpData.options.latitude == '' || bgmpData.options.longitude == '' || bgmpData.options.zoom == '' || bgmpData.options.infoWindowMaxWidth == '' )
  62.             {
  63.                 // @todo update w/ cluster options?
  64.                
  65.                 $( $.bgmp.canvas ).html( $.bgmp.name + " error: map options not set." );
  66.                 return;
  67.             }
  68.            
  69.             mapOptions =
  70.             {
  71.                 'zoom'                      : 15,//not working.bgmpData.options.zoom,
  72.                 'center'                    : new google.maps.LatLng( bgmpData.options.latitude, bgmpData.options.longitude ),
  73.                 'mapTypeId'                 : google.maps.MapTypeId[ bgmpData.options.type ],
  74.                 'mapTypeControl'            : bgmpData.options.typeControl == 'off' ? false : true,
  75.                 'mapTypeControlOptions'     : { style: google.maps.MapTypeControlStyle[ bgmpData.options.typeControl ] },
  76.                 'navigationControl'         : bgmpData.options.navigationControl == 'off' ? false : true,
  77.                 'navigationControlOptions'  : { style: google.maps.NavigationControlStyle[ bgmpData.options.navigationControl ] },
  78.                 'streetViewControl'         : bgmpData.options.streetViewControl
  79.             };
  80.            
  81.             // Override default width/heights from settings
  82.             $( '#bgmp_map-canvas' ).css( 'width', bgmpData.options.mapWidth ); //'100%');       // @todo use $.bgmp.canvas intead of hardcoding it?
  83.             $( '#bgmp_map-canvas' ).css( 'height', bgmpData.options.mapHeight ); // '100%');   Making map responsive.
  84.             // @todo this prevents users from using their own stylesheet?
  85.            
  86.            
  87.             // Create the map
  88.             try
  89.             {
  90.                 $.bgmp.map = new google.maps.Map( $.bgmp.canvas, mapOptions );
  91.             }
  92.             catch( e )
  93.             {
  94.                 $( $.bgmp.canvas ).html( $.bgmp.name + " error: couln't build map." );
  95.                 if( window.console )
  96.                     console.log( 'bgmp_buildMap: '+ e );
  97.                    
  98.                 return;
  99.             }
  100.            
  101.             $.bgmp.addPlacemarks( $.bgmp.map );     // @todo not supposed to add them when clustering is enabled? http://www.youtube.com/watch?v=Z2VF9uKbQjI
  102.            
  103.             if( bgmpData.options.clustering.enabled )
  104.             {
  105.                 $.bgmp.markerCluster = new MarkerClusterer(     // @todo should be .markerClusterer ?
  106.                     $.bgmp.map,
  107.                     $.bgmp.markers,
  108.                     {
  109.                         maxZoom     : bgmpData.options.clustering.maxZoom,
  110.                         gridSize    : bgmpData.options.clustering.gridSize,
  111.                         styles      : bgmpData.options.clustering.styles[ bgmpData.options.clustering.style ]
  112.                     }
  113.                 );
  114.             }
  115.         },
  116.        
  117.         /**
  118.          * Checks if the value is an integer. Slightly modified version of original.
  119.          * @author Invent Partners
  120.          * @link http://www.inventpartners.com/content/javascript_is_int
  121.          * @param mixed value
  122.          * @return bool
  123.          */
  124.         isInt : function( value )
  125.         {
  126.             if( !isNaN( value ) && parseFloat( value ) == parseInt( value ) )
  127.                 return true;
  128.             else
  129.                 return false;
  130.         },
  131.  
  132.         /**
  133.          * Pull the placemark posts from Wordpress' database and add them to the map
  134.          * @author Ian Dunn <ian@iandunn.name>
  135.          * @param object map Google Maps map
  136.          */
  137.         addPlacemarks : function( map )
  138.         {
  139.             // @todo - should probably refactor this since you pulled out the ajax. update phpdoc too
  140.            
  141.             if( bgmpData.markers.length > 0 )
  142.             {
  143.                 for( var m in bgmpData.markers )
  144.                 {
  145.                     $.bgmp.createMarker(
  146.                         map,
  147.                         bgmpData.markers[ m ][ 'title' ],
  148.                         bgmpData.markers[ m ][ 'latitude' ],
  149.                         bgmpData.markers[ m ][ 'longitude' ],
  150.                         bgmpData.markers[ m ][ 'details' ],
  151.                         bgmpData.markers[ m ][ 'icon' ],
  152.                         parseInt( bgmpData.markers[ m ][ 'zIndex' ] ),
  153.                         bgmpData.markers[ m ][ 'categories' ], //Added by Jesse 13/Dec
  154.                         bgmpData.markers[ m ][ 'address' ] //Added by Jesse 14/Dec
  155.                     );
  156.                 }
  157.             }
  158.         },
  159.  
  160.         /**
  161.          * Create a marker with an information window
  162.          * @author Ian Dunn <ian@iandunn.name>
  163.          * @param object map Google Maps map
  164.          * @param string title Placemark title
  165.          * @param float latituded
  166.          * @param float longitude
  167.          * @param string details Content of the infowinder
  168.          * @param string icon URL of the icon
  169.          * @param int zIndex The desired position in the placemark stacking order
  170.          * @param category array <-- added by Jesse 13/Dec
  171.          * @param string address
  172.          * @return bool True on success, false on failure
  173.          */
  174.         createMarker : function( map, title, latitude, longitude, details, icon, zIndex, categories, address )
  175.         {
  176.             // @todo - clean up variable names
  177.            
  178.             var infowindowcontent, infowindow, marker;
  179.            
  180.             if( isNaN( latitude ) || isNaN( longitude ) )
  181.             {
  182.                 if( window.console )
  183.                     console.log( "bgmp_createMarker(): "+ title +" latitude and longitude weren't valid." );
  184.                    
  185.                 return false;
  186.             }
  187.            
  188.             if( icon == null )
  189.             {
  190.                 // @todo - this check may not be needed anymore
  191.                
  192.                 if( window.console )
  193.                     console.log( "bgmp_createMarker(): "+ title +"  icon wasn't passed in." );
  194.                 return false;
  195.             }
  196.            
  197.             if( !$.bgmp.isInt( zIndex ) )
  198.             {
  199.                 //if( window.console )
  200.                     //console.log( "bgmp_createMarker():  "+ title +" z-index wasn't valid." ); // this would fire any time it's empty
  201.                
  202.                 zIndex = 0;
  203.             }
  204.            
  205.             infowindowcontent = '<div class="bgmp_placemark"> <h3>'+ title +'</h3> <div>'+ address + '<br />'+ details +'</div> </div>';
  206.            
  207.             try
  208.             {
  209.                 infowindow = new google.maps.InfoWindow( {
  210.                     content     : infowindowcontent,
  211.                     maxWidth    : bgmpData.options.infoWindowMaxWidth
  212.                 } );
  213.                
  214.                 // Replace commas with periods. Some (human) languages use commas to delimit the fraction from the whole number, but Google Maps doesn't accept that.
  215.                 latitude = parseFloat( latitude.replace( ',', '.' ) );
  216.                 longitude = parseFloat( longitude.replace( ',', '.' ) );
  217.                
  218.                 marker = new google.maps.Marker( {
  219.                     'position'  : new google.maps.LatLng( latitude, longitude ),
  220.                     'map'       : map,
  221.                     'icon'      : icon,
  222.                     'title'     : title,
  223.                     'zIndex'    : zIndex
  224.                 } );
  225.                 //Store Info Window Text in an array for easy access.
  226.                 $.bgmp.markers[marker['position']] = [details, address];
  227.                
  228.                 //Store Markers inside an array based on their categories. Jesse 13/Dec
  229.                 for (var s in categories) {
  230.                     title = categories[s]['name'];
  231.                     if (!$.bgmp.markers[title]){
  232.                         $.bgmp.markers[title] = [];
  233.                         $.bgmp.markers.push(title);
  234.                     }
  235.                     $.bgmp.markers[title].push(marker);
  236.                 }
  237.                
  238.                 //Need to store ALL markers inside an array to compensate for the possibility of multiple categories. Jesse 13/Dec
  239.                 $.bgmp.markers.all.push( marker );
  240.                
  241.                 google.maps.event.addListener( marker, 'click', function()
  242.                 {
  243.                     if( $.bgmp.previousInfoWindow != undefined )
  244.                         $.bgmp.previousInfoWindow.close();
  245.                    
  246.                     infowindow.open( map, marker );
  247.                     $.bgmp.previousInfoWindow = infowindow;
  248.                     $.bgmp.map.panTo(marker.getPosition());
  249.                     $.bgmp.map.setZoom(15);
  250.                 } );
  251.                
  252.                 return true;
  253.             }
  254.             catch( e )
  255.             {
  256.                 //$( $.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
  257.                 if( window.console )
  258.                     console.log( 'bgmp_createMarker: '+ e );
  259.             }
  260.         }
  261.     }; // end bgmp
  262.    
  263.     // Kick things off...
  264.     $( document ).ready( $.bgmp.init );
  265.    
  266. } // end bgmp_wrapper()
  267.  
  268. bgmp_wrapper( jQuery );
  269.  
  270.  
  271.  
  272. /************CUSTOM JAVASCRIPT************************/
  273. /****************************************************/
  274. $.geocoder;
  275. var html = '';
  276. var stepDisplay;
  277. var markerArray = [];  
  278. var bounds;
  279.  
  280. $(document).ready(function(){
  281.     //Add the Filtered Nav Div
  282.     if ($('#map').length) {
  283.         $('#map').append("<div id='filteredNav' /><hr /><div id='mapLocs' style='padding-left:30px;' />");
  284.         $.each($.bgmp.markers, function(index, arr) {
  285.             $('#filteredNav').append('<button class="fNav shown" value='+$.bgmp.markers[index]+''+'>'+$.bgmp.markers[index]+'</button>');          
  286.         });
  287.     }
  288.     //Verify that there are categories.
  289.     if ($('#filteredNav').length > 0) {    
  290.         //This isn't a good way to do this, but this will allow the ability to show multiple groups of markers.        
  291.         $('#filteredNav button').click(function() {
  292.             if(!$(this).hasClass('shown')) {
  293.                 $(this).addClass('shown');
  294.             } else { $(this).removeClass('shown'); }
  295.            
  296.             hideWindows();
  297.             hideMarkers();             
  298.             bounds = $.bgmp.map.getBounds();
  299.             //show only the markers that should be visible
  300.             showMarkers();         
  301.         });
  302.        
  303.        
  304.         //Center Map on Marker Clicked
  305.         $('#mapLocs').on('click','a', function(event) {
  306.             event.preventDefault();
  307.             var loc = $(this).attr('class').split('-');
  308.             $.bgmp.map.panTo($.bgmp.markers[loc[0]][loc[1]].getPosition());
  309.             $.bgmp.map.setZoom(15);
  310.         });
  311.     }
  312.  
  313.  
  314.     //Override Search
  315.     $('form[id=mapSearchForm]').submit(function(e) {
  316.         e.preventDefault();
  317.         codeAddress($(this).find('input[name="q"]').val());
  318.     });
  319.    
  320.     //http://stackoverflow.com/questions/4338490/google-map-event-bounds-changed-triggered-multiple-times-when-dragging
  321.     //https://developers.google.com/maps/documentation/javascript/events#EventListeners
  322.     google.maps.event.addListener($.bgmp.map, 'bounds_changed', function () {
  323.         bounds = $.bgmp.map.getBounds();
  324.         window.setTimeout(function() {
  325.             //hideWindows();
  326.             html = "";
  327.             //window.alert('Timer Fired');
  328.             showMarkers(); 
  329.         }, 300);
  330.     });
  331.     initialize();
  332. });
  333.  
  334. //Hide info window
  335. function hideWindows() {
  336.     if( $.bgmp.previousInfoWindow != undefined )
  337.         $.bgmp.previousInfoWindow.close();
  338. }
  339.  
  340.  
  341. //Hide all markers
  342. function hideMarkers() {
  343.     $.each($.bgmp.markers.all, function(index, marker) {
  344.         $.each(marker, function(key, value) {
  345.             marker.setVisible(false);
  346.         });
  347.     });
  348. }
  349.  
  350.  
  351. //Show Markers
  352. function showMarkers() {   
  353.     html="";
  354.     $('#filteredNav .shown').each(function() {
  355.         var check = $(this).attr('value');             
  356.         html = html + '<h3>'+check+'</h3><ul>';
  357.         $.each($.bgmp.markers[check], function(index, marker) {
  358.             $.each(marker, function(key, value) {
  359.                 marker.setVisible(true);
  360.                 //html = html+'key: '+key+' = value: '+value+';<br /> ';
  361.             });
  362.             if(bounds.contains(marker.getPosition())) {
  363.                 html = html +'<li style="list-style:none;"><a style="cursor:pointer;" class="'+check+'-'+index+'"><img style="float:left;" src="'+marker.getIcon()+'" /> ';
  364.                 html = html +marker.getTitle()+'</a> '+$.bgmp.markers[marker['position']][1]+'<div class="markDesc">'+$.bgmp.markers[marker['position']][0]+'</div></li>';                 
  365.             }
  366.         });
  367.         html = html+'</ul>';
  368.     });
  369.     $('#mapLocs').html(html);
  370. }
  371.  
  372. //Credit to: http://stackoverflow.com/questions/6140303/google-maps-v3-how-to-center-using-an-address-on-initialize
  373. function codeAddress(address) {
  374.     $.geocoder = new google.maps.Geocoder();
  375.     $.geocoder.geocode( { 'address': address}, function(results, status) {
  376.       if (status == google.maps.GeocoderStatus.OK) {
  377.         $.bgmp.map.panTo(results[0].geometry.location);
  378.       }
  379.     });
  380. }
  381.  
  382. //Google Maps Directions Information
  383. //https://developers.google.com/maps/documentation/javascript/directions
  384. var directionsDisplay;
  385. var directionsService = new google.maps.DirectionsService();
  386.  
  387. function initialize() {
  388.   directionsDisplay = new google.maps.DirectionsRenderer();
  389.   directionsDisplay.setMap($.bgmp.map);  
  390.   directionsDisplay.setPanel(document.getElementById('directionsPanel'));
  391.   stepDisplay = new google.maps.InfoWindow();
  392. }
  393.  
  394.     $('form[id=directionsForm]').submit(function(e) {
  395.         e.preventDefault();
  396.         calcRoute();
  397.     });
  398.  
  399. function calcRoute() {
  400.   var start = document.getElementById("start").value;
  401.   var end = document.getElementById("end").value;
  402.   var request = {
  403.     origin:start,
  404.     destination:end,
  405.     travelMode: google.maps.TravelMode.DRIVING
  406.   };
  407.   directionsService.route(request, function(result, status) {
  408.     if (status == google.maps.DirectionsStatus.OK) {
  409.       directionsDisplay.setDirections(result);
  410.       showSteps(result);
  411.     }
  412.   });
  413. }
  414.  
  415. function showSteps(directionResult) {
  416.         // For each step, place a marker, and add the text to the marker's
  417.         // info window. Also attach the marker to an array so we
  418.         // can keep track of it and remove it when calculating new
  419.         // routes.
  420.         var myRoute = directionResult.routes[0].legs[0];
  421.  
  422.         for (var i = 0; i < myRoute.steps.length; i++) {
  423.           var marker = new google.maps.Marker({
  424.             position: myRoute.steps[i].start_point,
  425.             map: $.bgmp.map
  426.           });
  427.           attachInstructionText(marker, myRoute.steps[i].instructions);
  428.           markerArray[i] = marker;
  429.         }
  430.       }
  431.  
  432.       function attachInstructionText(marker, text) {
  433.         google.maps.event.addListener(marker, 'click', function() {
  434.           // Open an info window when the marker is clicked on,
  435.           // containing the text of the step.
  436.           stepDisplay.setContent(text);
  437.           stepDisplay.open($.bgmp.map, marker);
  438.         });
  439.       }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement