Skip Navigation

[Resolved] Add a marker to a map dependent on user input

This support ticket is created 4 years ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+01:00)

This topic contains 10 replies, has 2 voices.

Last updated by Nigel 3 years, 11 months ago.

Assisted by: Nigel.

Author
Posts
#2165343

Tell us what you are trying to do?
I'd like to add a marker to a map that is specified by the user NOT their geocode position, but an address that they enter.

Is there any documentation that you are following?
No

Is there a similar example that we can see?
I am trying to emulate this hidden link - the results shown include a marker for the address the user entered rather than the location they are according to geocode.

What is the link to your site?
hidden link

#2165691

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

Hi Simon

This is proving tricky.

There's nothing built-in with Toolset that will let you add such a marker with the search location, but it should be possible with some code.

I'm most of the way there, so that the marker for the location is added when a search is submitted, but my problem is getting the map to redraw, because the marker may be added outside the bounds of the existing map and not be visible.

I'm consulting with the devs about getting that working, their initial pointers didn't work.

Leave it with me and I'll get back to you when I have a solution.

#2167733

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

It's not clear that our maps implementation includes an internal method to achieve this, and instead I've gone with using the Google Maps API directly to update the boundaries of the map to include the added marker for the search origin.

The marker is added via JavaScript on the front-end, but that code is assembled using PHP on the server so that some of the required data for coordinates etc. can be incorporated.

You'll need to add the following PHP, and the only thing you should need to change is the ID of the map ("map-12" in the same below):

/**
 * Add a marker for the search location to a map
 */
add_action( 'init', 'ts_distance_center_coordinates', 101 );
function ts_distance_center_coordinates(){

    if ( isset($_REQUEST['toolset_maps_distance_center']) )
    {
        $mapID = 'map-12'; // Edit

        $input = $_REQUEST['toolset_maps_distance_center'];
        $coords_array = Toolset_Addon_Maps_Common::get_coordinates( $input );

        $lat = $coords_array['lat'];
        $lon = $coords_array['lon'];
            
        $script = "
        ( function( $ ) {
            $( document ).bind( 'js_event_wpv_addon_maps_init_map_completed', function(){
                
                const mapid = '$mapID';
                const theMap = WPViews.view_addon_maps.get_map(mapid);
                const theLatLng = { lat: $lat, lng: $lon };

                const searchOrigin = new google.maps.Marker({
                    position: theLatLng,
                    theMap,
                    icon: image,
                    title: 'Search origin',
                });
                searchOrigin.setMap(theMap);

                // update bounds once map drawn
                google.maps.event.addListenerOnce(theMap, 'idle', function() {

                    const bounds = theMap.getBounds();
                    bounds.extend(theLatLng);
                    theMap.fitBounds(bounds);
                });
                
            });
        })( jQuery );
        ";

        // add inline script to front end
        wp_register_script( 'ts_distance_center_coords', '', array('jquery'), '', true );
        wp_enqueue_script( 'ts_distance_center_coords' );
        wp_add_inline_script( 'ts_distance_center_coords', $script);
    }
}

You can add that at Toolset > Settings > Custom Code.

You may want to add options for customising the marker icon etc., see the Google docs for more details:

hidden link

#2171213

Thank you for the work you've ut into this.

Unfortunately when I copied the code into the Custom Code settings as you suggested I get a status of Error.

Not sure how to resolve this.

#2171649

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

Do you have details of the error?

Did WordPress send you an email about the error, or did you see the error in your debug logs?

The error itself should point to the problem.

#2171731
screencapture-frw-one-wp-admin-admin-php-2021-09-17-09_20_50.png

The Error status is reported in the Custom Code section as soon as I saved it; it is hence marked as Status Inactive/Error.

The message consists of a regurgitation of the code prefixed by - Unexpected output of the code snippet.
I've enclosed a screen dump.

Apologies if I've done something stupid.

#2171761

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

Sorry, when you add a Code Snippet there is a required part at the top and you should add the custom code below that.

Edit your snippet and add this at the top, before the code I shared with you.

<?php
toolset_snippet_security_check() or die('Direct access is not allowed');

Then try to Run now the snippet, which will detect any such errors, in the absence of which you can activate the snippet.

Does that fix it?

#2171793

OK - the Error is now resolved, but a quick test didn't show anything on the map.

Should I be changing my page at all?
And yes I have changed the map ID!

#2171839

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

Sorry, I see an error on your site using this, and spot a problem where I had made a slight change on my test site but had the prior code in my clipboard before pasting it in my reply above.

You need to remove the line that has icon: image, so the complete code for the entire snippet (including the required code at the top) would be this:

<?php

toolset_snippet_security_check() or die( 'Direct access is not allowed' );

/**
 * Add a marker for the search location to a map
 */
add_action( 'init', 'ts_distance_center_coordinates', 101 );
function ts_distance_center_coordinates(){

    if ( isset($_REQUEST['toolset_maps_distance_center']) )
    {
        $mapID = 'map-12'; // Edit

        $input = $_REQUEST['toolset_maps_distance_center'];
        $coords_array = Toolset_Addon_Maps_Common::get_coordinates( $input );

        $lat = $coords_array['lat'];
        $lon = $coords_array['lon'];
            
        $script = "
        ( function( $ ) {
            $( document ).bind( 'js_event_wpv_addon_maps_init_map_completed', function(){
                
                const mapid = '$mapID';
                const theMap = WPViews.view_addon_maps.get_map(mapid);
                const theLatLng = { lat: $lat, lng: $lon };

                const searchOrigin = new google.maps.Marker({
                    position: theLatLng,
                    theMap,
                    title: 'Search origin',
                });
                searchOrigin.setMap(theMap);

                // update bounds once map drawn
                google.maps.event.addListenerOnce(theMap, 'idle', function() {

                    const bounds = theMap.getBounds();
                    bounds.extend(theLatLng);
                    theMap.fitBounds(bounds);
                });
                
            });
        })( jQuery );
        ";

        // add inline script to front end
        wp_register_script( 'ts_distance_center_coords', '', array('jquery'), '', true );
        wp_enqueue_script( 'ts_distance_center_coords' );
        wp_add_inline_script( 'ts_distance_center_coords', $script);
    }
}
#2171875

Brilliant!

So one tweak - can we specify a different map marker icon for this so that it stands out a bit better?
And can it have some hint content?

#2171957

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

Yes, you can customise the marker as described in the Google API docs, same link I shared before: hidden link

In the updated code below I use one of the alternative icons provided by the Toolset Maps plugin itself, but you could provide an alternative yourself. I also added an animation where the pin is dropped onto the map. Also, a tooltip is already included (the title attribute currently set to "Search origin").

The Google API is pretty flexible and you can make changes to the marker as required by updating options in the added code.

Here's the updated version:

<?php

toolset_snippet_security_check() or die( 'Direct access is not allowed' );

/**
 * Add a marker for the search location to a map
 */
add_action( 'init', 'ts_distance_center_coordinates', 101 );
function ts_distance_center_coordinates(){

    if ( isset($_REQUEST['toolset_maps_distance_center']) )
    {
        $mapID = 'map-12'; // Edit

        $input = $_REQUEST['toolset_maps_distance_center'];
        $coords_array = Toolset_Addon_Maps_Common::get_coordinates( $input );

        $lat = $coords_array['lat'];
        $lon = $coords_array['lon'];
            
        $script = "
        ( function( $ ) {
            $( document ).bind( 'js_event_wpv_addon_maps_init_map_completed', function(){
                
                const mapid = '$mapID';
                const theMap = WPViews.view_addon_maps.get_map(mapid);
                const theLatLng = { lat: $lat, lng: $lon };

                const searchIcon = '<em><u>hidden link</u></em>';

                const searchOrigin = new google.maps.Marker({
                    position: theLatLng,
                    theMap,
                    icon: searchIcon,
                    animation: google.maps.Animation.DROP,
                    title: 'Search origin',
                });
                searchOrigin.setMap(theMap);

                // update bounds once map drawn
                google.maps.event.addListenerOnce(theMap, 'idle', function() {

                    const bounds = theMap.getBounds();
                    bounds.extend(theLatLng);
                    theMap.fitBounds(bounds);
                });
                
            });
        })( jQuery );
        ";

        // add inline script to front end
        wp_register_script( 'ts_distance_center_coords', '', array('jquery'), '', true );
        wp_enqueue_script( 'ts_distance_center_coords' );
        wp_add_inline_script( 'ts_distance_center_coords', $script);
    }
}