Using Mapbox GL JS Map

Hello,

I am working on adding a store finder to my website using Mapbox GL JS. I am following the tutorial here https://www.notion.so/Lunchbox-Store-Locator-8d803603b3814ee8909c42dfaac48491. All works well for me until I reach the step titled “Add Data to the Map”. In this section I am adding js code to add map markers to the map. When I add the js in either a text element or raw content element I get an error in Pro says “Failed. Unable to save.” I am then force logged out of Wordpress.

I am not sure what I am doing wrong. The code I am pasting in that forces the page not to be able to save and force logs me out is below. Any suggestions or help is greatly appreciated!

map.on(‘load’, function (e) {
/**
* This is where your ‘.addLayer()’ used to be, instead
* add only the source without styling a layer
*/
map.addSource(“places”, {
“type”: “geojson”,
“data”: stores
});

    /**
     * Add all the things to the page:
     * - The location listings on the side of the page
     * - The markers onto the map
    */
    buildLocationList(stores);
    addMarkers();
  });

/**
* Add a marker to the map for every store listing.
*/
function addMarkers() {
/
For each feature in the GeoJSON object above: /
stores.features.forEach(function(marker) {
/
Create a div element for the marker. /
var el = document.createElement(‘div’);
/
Assign a unique id to the marker. /
el.id = “marker-” + marker.properties.id;
/
Assign the marker class to each marker for styling. */
el.className = ‘marker’;

      /**
       * Create a marker using the div element
       * defined above and add it to the map.
      **/
      new mapboxgl.Marker(el, { offset: [0, -23] })
        .setLngLat(marker.geometry.coordinates)
        .addTo(map);

      /**
       * Listen to the element and when it is clicked, do three things:
       * 1. Fly to the point
       * 2. Close all other popups and display popup for clicked store
       * 3. Highlight listing in sidebar (and remove highlight for all other listings)
      **/
      el.addEventListener('click', function(e){
        /* Fly to the point */
        flyToStore(marker);
        /* Close all other popups and display popup for clicked store */
        createPopUp(marker);
        /* Highlight listing in sidebar */
        var activeItem = document.getElementsByClassName('active');
        e.stopPropagation();
        if (activeItem[0]) {
          activeItem[0].classList.remove('active');
        }
        var listing = document.getElementById('listing-' + marker.properties.id);
        listing.classList.add('active');
      });
    });
  }

function buildLocationList(data) {
data.features.forEach(function(store, i){
/**
* Create a shortcut for store.properties,
* which will be used several times below.
**/
var prop = store.properties;

      /* Add a new listing section to the sidebar. */
      var listings = document.getElementById('listings');
      var listing = listings.appendChild(document.createElement('div'));
      /* Assign a unique `id` to the listing. */
      listing.id = "listing-" + prop.id;
      /* Assign the `item` class to each listing for styling. */
      listing.className = 'item';

      /* Add the link to the individual listing created above. */
      var link = listing.appendChild(document.createElement('a'));
      link.href = '#';
      link.className = 'title';
      link.id = "link-" + prop.id;
      link.innerHTML = prop.Name;

      /* Add details to the individual listing. */
      var details = listing.appendChild(document.createElement('div'));
      if (prop.Address) {
        details.innerHTML += prop.Address;
      }

      /**
       * Listen to the element and when it is clicked, do four things:
       * 1. Update the `currentFeature` to the store associated with the clicked link
       * 2. Fly to the point
       * 3. Close all other popups and display popup for clicked store
       * 4. Highlight listing in sidebar (and remove highlight for all other listings)
      **/
      link.addEventListener('click', function(e){
        for (var i=0; i < data.features.length; i++) {
          if (this.id === "link-" + data.features[i].properties.id) {
            var clickedListing = data.features[i];
            flyToStore(clickedListing);
            createPopUp(clickedListing);
          }
        }
        var activeItem = document.getElementsByClassName('active');
        if (activeItem[0]) {
          activeItem[0].classList.remove('active');
        }
        this.parentNode.classList.add('active');
      });
    });
  }
		
		// This will let you use the .remove() function later on
    if (!('remove' in Element.prototype)) {
      Element.prototype.remove = function() {
        if (this.parentNode) {
            this.parentNode.removeChild(this);
        }
      };
    }

  /*
   * Use Mapbox GL JS's `flyTo` to move the camera smoothly
   * a given center point.
  **/
  function flyToStore(currentFeature) {
    map.flyTo({
      center: currentFeature.geometry.coordinates,
      zoom: 15
    });
  }

Hi @mattcaldwell,

Thanks for reaching out.

Since your custom code is having an issue with your website and the problem is not coming from our theme, Regretfully, we can’t help you to troubleshoot your issue because 3rd party integration is outside the scope of our theme support. Please seek help for a 3rd party developer or you can avail our One to help you with your concern.

Hope that helps and thank you for understanding.

Hi Cramaton,

Thanks for your response. I don’t believe the issue is the 3rd party code, I am able to add the code and see the map working within the pro editor, but i am unable to save the page. The pro editor just tells me save failed and content was unable to save. No specific error.

Hey @mattcaldwell,

This usually happens when there is an invalid / unsupported character, HTML tag or syntax error in your content, the builder fails to save such content. Instead of pasting your JS which may have syntax error inside the content builder / Cornerstone, I’d recommend you to use child theme instead to include your script on a specific page.

You can follow this thread Adding code and paste the code in your child theme’s functions.php file. Using conditional tag is_page() you can make sure that the code doesn’t run on all other pages (see https://developer.wordpress.org/reference/functions/is_page/) for example:

function my_custom_script() {
	if ( is_page( 2 ) ) {
		<!-- Replace this line with your JS code -->
	}
}
add_action('wp_footer','my_custom_script');

Where 2 is the page ID where you want to execute your code. To find out page IDs please follow https://theme.co/docs/how-to-locate-post-ids

Please note that custom development is outside the scope of our support. Issues that might arise from the use of custom code and further enhancements should be directed to a third party developer.

Hope this helps!

Hi @nabeel,

Thanks for these suggestions. I actually just made an html file on my desktop, inserted the code from the tutorial, and it works off the local file. There is something that Pro does not like within the code, because I cannot save it within a page.

I did figure out an alternative solution for myself. I simply uploaded the html file to my wordpress directory and the page works perfectly on my site. I can now embed the custom map within a pro page if needed. Just wanted to share in case anyone else runs into this in the future!

Best,

Matt

@mattcaldwell,

We are glad that you are able to solve your issue.

Thank you.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.