Menü schliessen
Created: July 6th 2021
Last updated: July 6th 2021
Categories: Advanced Custom Fields,  IT Development,  Php,  Wordpress
Author: Miljan Puzovic

Custom marker icon and popup content in ACF OpenStreetMap Field

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

ACF OpenStreetMap Field provides us with an easy way to implement OpenStreet map in WordPress websites. But sometimes we have an request to change marker icon or to show some custom popup content above marker. By default, popup content is and address entered in backend.

Default marker icon and popup content when using ACF OpenStreetMap Field plugin

Default marker icon and popup content when using ACF OpenStreetMap Field plugin

Luckily ACF OpenStreetMap provides us with useful WordPress filters and JS events for manipulating with such content.

Changing the marker icon

In order to change icon we can use this code in functions.php:

function replace_acf_osm_marker_icon( $icon ): array {
    return [
        'iconUrl'    => get_template_directory_uri()."/images/map-marker.svg",
        'iconSize'   => [ 26, 40 ],
        'iconAnchor' => [ 13, 10 ],
    ];
}
add_filter( 'acf_osm_marker_icon', 'replace_acf_osm_marker_icon' );

where iconSize and icon iconAnchor sizes are defined as seen here.

Changing the popup content

Content of the popup can be printed with PHP into a JavaScript variable (map_label constant in our case) or provided differently, and JS code for changing the content of the popup looks like this:

$(document).on('acf-osm-map-created', function(e){
    let map = e.detail.map;
    map.eachLayer(function (layer) { 
        if (layer.options.label !== undefined) {
            var popup = layer.getPopup();
            if (map_label !== null) {
                popup.setContent(map_label);
            }
            layer.openPopup(); // optionally open this popup
        }
    });
});

Finally, changes has been applied and result looks like this:

Changed Marker icon and popup content after WordPress filter and JS events has been used

Changed Marker icon and popup content after WordPress filter and JS events has been used

You can also take a look at our post about ACF OpenStreetMap Field plugin.