Aleš Sýkora / November 28, 2023 / 0 comments

Fluent Forms maps input (usable with Toolset Maps too)

Post summary: UPDATE! Automatic geolocation has been added to the map :). Enjoy! If you want to add map field with click to put marker function and save the GPS data, you can use the Google Maps API with Fluent Forms. You will need Google Maps API Key and plugin for custom code snippets (you can also…

UPDATE! Automatic geolocation has been added to the map :). Enjoy!

If you want to add map field with click to put marker function and save the GPS data, you can use the Google Maps API with Fluent Forms.

You will need Google Maps API Key and plugin for custom code snippets (you can also build your own plugin from the code by saving as PHP and adding Plugin header info to the file).

I am also using Advanced scripts for creation of Shortcode.

Prepare Fluent form

As a first step, create two numeric fields in Fluent Forms and add them this name attributes:
latInput
lngInput

Name attribute in fluent forms
Numeric fields for Latitude and Longtitude

As a second thing, create a shortcode field and put this shortcode inside:

[twiki_ff_google_maps]
Fluent Forms Shortcode field

Prepare the Map

Get your Google Maps API key

Add Google Maps script below to Advanced scripts and save it as a shortcode:

Using script as a shortcode in Advanced Scripts
<style type="text/css">
.acf-map {
    width: 100%;
    height: 400px;
    border: #ccc solid 1px;
    margin: 20px 0;
}

// Fixes potential theme css conflict.
.acf-map img {
   max-width: inherit !important;
}
.acf-map .custom-map-control-button {
  background-color: #fff;
  border: 0;
  border-radius: 2px;
  box-shadow: 0 1px 4px -1px rgba(0, 0, 0, 0.3);
  margin: 10px;
  padding: 0 0.5em;
  font: 400 18px Roboto, Arial, sans-serif;
  overflow: hidden;
  height: 40px;
  cursor: pointer;
}
.acf-map .custom-map-control-button:hover {
  background: rgb(235, 235, 235);
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-GOOGLE-API-KEY"></script>
<script type="text/javascript">
(function( $ ) {

/**
 * initMap
 *
 * Renders a Google Map onto the selected jQuery element
 *
 * @date    22/10/19
 * @since   5.8.6
 *
 * @param   jQuery $el The jQuery element.
 * @return  object The map instance.
 */
function initMap( $el ) {
    
    // Create gerenic map.
    var mapArgs = {
        zoom        : $el.data('zoom') || 16,
        mapTypeId   : google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map( $el[0], mapArgs );
    
    infoWindow = new google.maps.InfoWindow();
    
    // Init marker handlers
    initMarkers(map);

    // Center map to static location
    centerMap( map );

    // Return map instance.
    return map;
}

function updateFields(lat, lng) { 
    $("input[name='latInput']").val(lat.toFixed(6));
    $("input[name='lngInput']").val(lng.toFixed(6)); 
}

/**
 * initMarkers
 */

function initMarkers( map ) {

    var marker;

    google.maps.event.addListener(map, 'click', function(event) {
       placeMarker(event.latLng);
       updateFields(event.latLng.lat(), event.latLng.lng());
    });

    function placeMarker(location) {

        if (marker == null)
        {
            marker = new google.maps.Marker({
                position: location,
                map: map,
                draggable:true,
                animation: google.maps.Animation.DROP,
                title:"Drag me!"
            });

            function handleDrag(event) {
                updateFields(event.latLng.lat(), event.latLng.lng());
            }

            marker.addListener("drag", handleDrag)
            marker.addListener("dragend", handleDrag)
        } 
        else 
        {
            marker.setPosition(location); 
        }

    }
    
    const locationButton = document.createElement("button");

  locationButton.textContent = "Pan to Current Location";
  locationButton.classList.add("custom-map-control-button");
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
  locationButton.addEventListener("click", (event) => {
      event.preventDefault();
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };
          placeMarker(pos);
          updateFields(pos.lat, pos.lng);
          map.setCenter(pos);
        },
        () => {
          handleLocationError(true, map.getCenter());
        }
      );
    } 
  });


}

/**
 * centerMap
 */
function centerMap( map ) {
    var location = {lat: 49.81749199999999, lng: 15.472962}; // Czech republic
    map.setCenter(location);
}

// Render maps on page load.
$(document).ready(function(){
    $('.acf-map').each(function(){
        var map = initMap( $(this) );
    });
});
})(jQuery);
</script>

<div class="acf-map" data-zoom="7">
<div class="marker" data-lat="" data-lng=""></div>
</div>

If you do not have Advanced scripts, just create a new shortcode and put the code below into function:

<?php function twiki_ff_map() {
    ob_start();
?>
    /*PUT THE CODE of MAP HERE*/
<?php
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}
add_shortcode( 'twiki_ff_google_maps', 'twiki_ff_map' );

The result

Save the form and use it on your website page or post or whenever you want. You should see this:

Variant for Toolset Forms

This works for Toolset Forms for creating posts as well. But instead of creating custom fields for latitude and longtitude, just create one custom field of Map type. Then in form use two generic text fields named “latInput” and “lngInput”. After making it working you will need to save data from generic fields to the custom map field. So change the

wpcf-custom-map-field-slug

to your Map fields slug and use this custom code to save the data on form saving:

<?php
add_action('cred_save_data', 'custom_function',10,2);
function custom_function($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==83) //your form ID
      
    {
        $lat= $_POST["latInput"];
        $long = $_POST["lngInput"];
        $gps = "{".$lat.",".$long."}";
 
     update_post_meta($post_id, 'wpcf-custom-map-field-slug', $gps); 
     
    }
}
?>

Fuel my passion for writing with a beer🍺

Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻

0 comments

Share Your Thoughts