ASP.NET

Multiple Map locations using Sitecore 9 Update 2 Forms

This blog helps the developers in building a Custom Form Element called Multiple Map locations using Sitecore 9 forms.

Below are the steps to be followed:

1.Create a field template

Path : /sitecore/templates/System/Forms/Fields/MapMultipleLocations

Fields:

  1. Location – Single-Line Text

  2. Latitude – Single-Line Text

  3. Longitude – Single-Line Text

  4. Height – Integer

  5. Width – Integer

  6. Zoom – Integer

  7. MapType – Single-Line Text

Note : Do not forget to set the Standard values.

2.Create a class that derives from the FieldViewModel class.

For Example:

using Sitecore.ExperienceForms.Mvc.Models.Fields;
using Sitecore.Data.Items;
using Sitecore;
using System.Linq;

namespace TA_TechBlog_Demo
{
    public class MapWithMultipleLocations : FieldViewModel
    {
        public string Height { get; set; }
        public string Width { get; set; }
        public string MapType { get; set; }
        public int? Zoom { get; set; }
        public string LocationToolTip { get; set; }
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public string CentralOrDefaultLocation { get; set; }

        protected override void InitItemProperties(Item item)
        {
            base.InitItemProperties(item);
            Height = item["Height"];
            Width = item["Width"];
            MapType = item["MapType"];
            Zoom = MainUtil.GetInt(item["Zoom"], 0);
            LocationToolTip = item["LocationToolTip"];
            Latitude = item["Latitude"];
            Longitude = item["Longitude"];
            CentralOrDefaultLocation = item["CentralOrDefaultLocation"];
        }
        protected override void UpdateItemFields(Item item)
        {
            base.UpdateItemFields(item);
            item["Height"] = Height;
            item["Width"] = Width;
            item["MapType"] = MapType;
            item["Zoom"] = Zoom.ToString();
            item["LocationToolTip"] = LocationToolTip;
            item["Latitude"] = Latitude;
            item["Longitude"] = Longitude;
            item["CentralOrDefaultLocation"] = CentralOrDefaultLocation;
        }
    }
}

The class should include:

1.The properties of the custom form element.

2.Override the InitItemProperties() method (to get the standard values when the element is dragged on to the form).

3.Override UpdateItemFields()  method.

3.Build the project and deploy the dll to the Sitecore website bin folder.

4.Create the razor view file as below

@model TA_TechBlog_Demo.MapWithMultipleLocations

<div id="map" style="width: @Model.Width; height: @Model.Height;"></div>

<script async defer src="https://maps.google.com/maps/api/js?key=AIzaSyCOcUQFZXDO3qYsWvM7pJLnpcMZJF_CWKU&callback=initMap" type="text/javascript">
</script>

            <script type="text/javascript">
                var places = "@Model.LocationToolTip";
                var placeArray = places.split(',');
                var longitudes = "@Model.Longitude";
                var latitudes = "@Model.Latitude";
                var latitudeArray = latitudes.split(',');
                var locationslength = latitudeArray.length;
                var longitudeArray = longitudes.split(',');
                var locations = [];
                var latsum = 0;
                var latcenter = 0;
                var longsum = 0;
                var longcenter = 0;
                for (var i = 0; i < placeArray.length; i++) {
                    locations[i] = [placeArray[i], latitudeArray[i], longitudeArray[i]];
                    longsum += parseFloat(longitudeArray[i]);
                    latsum += parseFloat(latitudeArray[i]);
                }
                latcenter = latsum / latitudeArray.length;
                longcenter = longsum / longitudeArray.length;

function initMap(){  
  var map = new google.maps.Map(document.getElementById('map'), {
        zoom: @Model.Zoom,
        center: new google.maps.LatLng(latcenter, longcenter),
        mapTypeId: google.maps.MapTypeId.@Model.MapType
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
	}
  </script>

 

 The View includes:

1.The google maps API added in the script.

2.initmap() function which contains updated values from the form designer.

5. Add the razor view file to the new class library project that you created earlier.

Generally the default razor views for Sitecore Forms are stored in:

Website/Views/FormBuilder/FieldTemplates’.

6.Add sections to the Form elements pane:

In this example, for the MultipleMapLocations element, we want the user to be able to set the Location, Latitude, Longitude, Height, Width, Zoom, MapType.

1.In Sitecore Rocks, expand the core database and right-click the Settings folder that contains the layout parameters for all field property editors:

/sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Settings’

Note: The templates in the Core Database will not be available at the regular templates folder in the Sitecore instance.Therefore we use Sitecore Rocks.

2.Create a new item for example MultipleMapLocations using Form Parameters template.

3.To add the new sections for your custom element, under the MultipleMapLocations item we just created, create a new item for example Details using FormSection template.

4.To set the properties of the Custom Form Element, Create new items under the details section using the FormTextBox Parameters template.

7.Configure the field editor parameters

Open the Zoom item and navigate to the Form section. populate the FormLabel, IsLabelOnTop and BindingConfiguration fields.

Note:

-For consistency, it is recommended that you select ‘IsLabelOnTop’ checkbox for all field editor properties.

– Field model property name should be in ‘camelCase’.

 

8.In the Details section, reference the field editors in the following fields:

ConfigurationItem – specify the parameters for the Speak Expander. You can reuse the DetailsExpander item in :

/sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Common/Sections’

ControlDefinitions– specify the field editors that display in the Form elements pane, in order of reference. You can reuse the Fieldname item in:

/sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Common/Details’

9.In ControlDefinitions, select items you created earlier as below:

 

 

 

10.Create the section item using the FormSection template, for example, name it Styling.

11.Edit the following fields of Styling item, in the Data section:

ConfigurationItem – add the reference to the Styling Expander:

/sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Common/Sections/StylingExpander’

ControlDefinitions – add the reference to the CSS Class:

/sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Common/Styling/CssClass’

 

12.Create the field type item:

Create a new item at ‘/sitecore/system/Settings/Forms/Field Types/Basic’ folder location based on

/System/Forms/Field Type’ template.

-Populate the View Path, Model Type and Property Editor fields accordingly.

13.In the Appearance section, edit the Icon, BackgroundColor fields.

Populate the Field template field with the one you created previously.

Result : Now you will be able to see the newly created custom form component in the element pane.

                                                                 

Demo on Usage:

Create a sample form and drag and drop the MultipleMapLocations component on to the form and populate the fields accordingly.

Note: Enter the values of multiple locations separated with comma.

                                   

The entered locations will be highlighted in the map as above.

About The Author

Leave a Reply

*