Center the map on a marker and trigger its event


Deep-link to a map page so it centers on a listing and optionally fires the marker event (for example click to open the infobox).

1. Link with post_id

From any page, link to your map URL with a query argument:

https://www.example.com/map/?post_id=15

15 is the WordPress post ID of the location.

2. Add this filter

In your child theme functions.php:

/**
 * Focus Progress Map on ?post_id=… and trigger the marker click.
 */
function cspm_focus_map_on_marker_with_event( $default, $map_id ) {

	if ( ! isset( $_GET['post_id'] ) ) {
		return;
	}

	$post_id   = absint( $_GET['post_id'] );
	$latitude  = get_post_meta( $post_id, CSPM_LATITUDE_FIELD, true );
	$longitude = get_post_meta( $post_id, CSPM_LONGITUDE_FIELD, true );

	if ( '' === $latitude || '' === $longitude ) {
		return;
	}

	$output = "
	setTimeout(function(){
		cspm_center_map_at_point(plugin_map, map_id, '" . esc_js( $latitude ) . "', '" . esc_js( $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 );

Customize

  • Replace 'click' with another Google Maps marker event if needed.
  • Increase the timeouts if your map loads markers slowly (clustering, many pins).
  • Limit to one map ID if several maps share the page.

Related

  • Shortcode attribute center_at on
Top