Center the map on a specific marker when the page loads and trigger the marker’s event


This tutorial will show you how to center the map on a specific marker when the map page loads and, once centered, trigger the marker’s event.

  1. For this to work, you need to add the post_id attribute to the URL. For example, if you’re navigating from your homepage (www.website.com) to your map page (www.website.com/map), you must append the post_id attribute with the actual post ID as its value. In this case, the URL should look like www.website.com/map/?post_id=15, where 15 represents the real post ID.
  2. Edit the file “functions.php” of your theme/child theme and copy/paste the following code in it:
    function cspm_focus_map_on_marker_with_event($default, $map_id){
    	
    	if(isset($_GET['post_id'])){
    		
    		$post_id = esc_attr($_GET['post_id']);
    		
    		$latitude = get_post_meta($post_id, CSPM_LATITUDE_FIELD, true);
    		$longitude = get_post_meta($post_id, CSPM_LONGITUDE_FIELD, true);
    	
    		$output = "
    		setTimeout(function(){
    			cspm_center_map_at_point(plugin_map, map_id, '".$latitude."', '".$longitude."', 'zoom');
    			setTimeout(function(){
                    plugin_map.gmap3({
                        exec: {
                            name: 'marker',
                            all: true,
                            func: function(data){
                                    var marker = data.object;
                                    var post_id = ".$post_id.";
                                    if(marker.post_id == post_id){
                                        new google.maps.event.trigger(marker, 'click');
                                    }
                                }
                            }
                        });
                    }, 500);
    		}, 500);";
    		
    		echo $output;
    	
    	}
    	
    }
    add_filter('cspm_after_map_load', 'cspm_focus_map_on_marker_with_event', 10, 2);

The code above uses the “click” event. To use a different event, simply replace 'click' in the code. Be sure to check the list of all available events!


In the same context