JReviews logo
Guides My site
← All guides Community guide

Display GPX, KML, and GeoJSON attachments on a MapsPro widget

Josh Alejandro
Thread started by Josh. Contributors Alejandro, Josh.
Thread started
Last updated

What you’ll achieve

Draw the routes and shapes from a listing’s GPX, KML, and GeoJSON attachments on a MapsPro map widget.

My site

Platform
JReviews version

Draw the routes and shapes from a listing's GPX, KML, and GeoJSON attachments on a MapsPro map widget. These files hold map data, such as a hiking route recorded by a GPS app (GPX), a path drawn in Google Earth (KML), or a park boundary (GeoJSON). MapsPro converts GPX and KML files automatically, so you attach them as they are. For example, a trail listing with a trail.gpx attachment shows the trail line on the MapsPro map widget on that trail's page.

JReviews 6 Early Access

Choose the map you want to change

A listing page can show two different maps:

  • The listing's own map. This is the Map section of the listing page. It shows the listing's location. With the Early Access listing detail page turned on, this map already draws the listing's GPX, KML, and GeoJSON attachments. You don't need this guide or any code for it.
  • A MapsPro map widget. This is a separate map that you create under Site Widgets and place on listing pages. It shows nearby listings as markers. It does not draw attachments unless you turn on Show listing GPS tracks.

This guide is for attaching the files, placing the widget, and turning on that setting.

Turn on the Early Access listing detail page

  1. Open the JReviews dashboard and select Manage Early Access.
  2. In the Early Access Settings panel, turn on Listing Detail Page if it is off.

Allow GPX, KML, and GeoJSON attachments

  1. Open Configuration > Media Settings and select the Attachments tab.
  2. In Allowed File Extensions, add gpx, kml, and geojson at the end of the list, separated by commas and without dots. For example, zip,pdf,gpx,kml,geojson. Add only the types you plan to attach.
  3. Select Save at the top of the page.

Attach a GPX, KML, or GeoJSON file to a listing

If you don't have a file yet, export a GPX file from a GPS app or a KML file from Google Earth. You can also test with the GeoJSON file below: save it as test.geojson in a text editor. Replace the numbers with points near your listing. To find a point, open your listing's address in Google Maps and right-click the map: the first line of the menu shows the latitude and longitude. In the file, write each point as longitude first, then latitude, the reverse of the order Google Maps shows.

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "LineString",
        "coordinates": [[-71.0600, 42.3580], [-71.0550, 42.3610], [-71.0500, 42.3600]]
      }
    }
  ]
}
  1. Open the listing on your site and select Upload media.
  2. Drag the .gpx, .kml, or .geojson file into the upload area, or select browse and choose it.
  3. Select Submit. A site administrator's upload is published right away, and the page says it is now live on the website.

Create the map widget

  1. In the JReviews admin, open Setup > Site Widgets and select New.
  2. In Widget Type, type Maps, select Maps, and then select Start from Scratch.
  3. Give the widget a title, for example Trail map.
  4. Set Functionality Mode to Listings in proximity to current listing. The map then opens on the listing being viewed and shows the listings within Radius. If you leave Radius empty, the map uses 10.
  5. Turn on Show listing GPS tracks. The widget then draws this listing's GPX, KML, and GeoJSON attachments when it is on a listing detail page. Other map widgets stay as they are.
  6. Optionally turn on Show elevation scrubber if you want hover and click on the route to step through elevation. Leave it off if waypoints should stay easy to use.
  7. Save the widget.
  8. Place the widget on listing pages as described below. You do not need the Shortcode ID for drawing attachments.

Joomla. On the widget's edit page, select Publish as Joomla Module, then Create Module. In the module, choose a Position and, on the Menu Assignment tab, assign it to the pages that show your listings. Save the module. The module gets its own number, which is not the Shortcode ID either.

WordPress. Go to Appearance > Widgets and add the (JReviews) Universal Widget to a sidebar that your theme shows on listing pages. Do not use the separate (MapsPro) Map widget. In the widget's JReviews Widget list, select your map widget; the list shows each widget's Shortcode ID in brackets. Select the widget's Save button.

Open the listing from the previous step and scroll to the place where your sidebar or module position appears. The map widget should be there, in addition to the listing's own Map section. Named waypoints show as diamonds on the route. Hover a diamond for its name and elevation.

Check the result

Open the listing with the GPX, KML, or GeoJSON attachment. The map widget draws the routes, named waypoints as diamonds, and nearby listing markers. Hover a diamond for its name and elevation.

If you don't see the shapes:

  • Make sure the attachment is published and its file name ends in .gpx, .kml, or .geojson.
  • Make sure the person viewing the page is allowed to download attachments. A visitor who cannot download the file does not see its shapes. To change who can download an attachment, open Browse > Media in the JReviews admin, edit the attachment, and set its Access level.
  • Make sure Show listing GPS tracks is on for this widget.
  • Make sure the widget is on a listing detail page. Browse maps and widgets that are not on a listing page do not load that listing's attachments.

JReviews 5 and v6 Legacy

Add the code to your overrides

Use templates/jreviews_overrides/filters/filter_functions.php.

Use jreviews_overrides/filters/filter_functions.php.

  • If filter_functions.php already exists, add the lines marked with + in the next step at the end of the file. The copy button copies only those lines.
  • If you are creating filter_functions.php, type the two dimmed lines first, then add the marked lines below them.

Add listing attachments as map layers

Joomla. Create a MapsPro module and set Functionality Mode, under Pre-defined Filters, to Listings in proximity to current listing. Choose a Position that your template shows on listing pages, and assign the module to the pages that show your listings.

WordPress. Add a MapsPro widget and set Functionality Mode, under Pre-defined Filters, to Listings in proximity to current listing. Place it in a sidebar that your theme shows on listing pages.

This example adds the routes and shapes to the proximity map and leaves the separate listing detail map unchanged. Use only one MapsPro module or widget of any kind on the page. With two, both maps draw every shape twice. The JavaScript event identifies this map as module.

Prepare the attachments and map

MapsPro converts GPX and KML files to map shapes, so the same code handles all three file types.

  1. In Access Settings > Media > Uploads for Listings, select the user groups allowed to upload Attachments. If no group is selected, uploads fail with an "invalid extension" message.
  2. In Media Settings > Attachments > Allowed File Extensions, allow gpx, kml, and geojson as needed.
  3. Open the listing whose detail page contains the proximity map and select Add Media. Upload a GPX, KML, or GeoJSON file as a published attachment. For your first check, use a GPX file from a GPS app, a KML file from Google Earth, or a small GeoJSON FeatureCollection with coordinates near the listing.

Add the map filter

Add the filter marked with +.

<?php
defined('MVC_FRAMEWORK') or die;

/* Add GPX, KML, and GeoJSON support to module/widget */


function add_geo_layers_to_map_module($output, $params)
{
    $request = new FWD\Illuminate\Http\Request($params['params']);

    if ($request->option != 'com_content' || $request->view != 'article' || ! $request->id) {
        return $output;
    }

    $attachments = JReviews\App\Models\Media::query()
            ->coreExtension()
            ->notCommentMedia()
            ->where('listing_id', $request->id)
            ->whereIn('file_extension', ['gpx', 'kml', 'geojson'])
            ->attachment()
            ->published()
            ->get();

    S2App::import('Model', 'media', 'jreviews');
    $Media = ClassRegistry::getClass('MediaModel');
    $permissions = S2Object::make('perm');

    $attachments = $attachments->filter(function ($attachment) use ($Media, $permissions) {
        $media = $Media->findRow(['conditions' => [
            'Media.media_id = ' . (int) $attachment->media_id,
            'Media.media_type = "attachment"',
            'Media.published = 1',
            'Media.approved = 1',
        ]]);

        if (!$media) {
            return false;
        }

        return $permissions->__('media')->setMedia($media)->canDownload();
    });

    if ($attachments->isEmpty()) {
        return $output;
    }

    // MapsPro returns every file as GeoJSON from its maps.geojson route.
    $geo_layers = $attachments
        ->map(fn ($attachment) => jr_route_ajax('maps.geojson', ['file' => $attachment->media_id]))
        ->values()
        ->toJson();

    $script = "
    <script>
    document.addEventListener('jr-map-initialized', function(event) {
        if (event.detail.type !== 'module') {
            return;
        }
        console.log(`Geo layers filter: \${event.detail.type} map initialized`);
        const layers = $geo_layers;
        let map = jQuery(event.target).data('map');
        layers.forEach(url => jreviews.addGeoJSONLayer(map, url))
    });

    jreviews.addGeoJSONLayer = async function(map, url) {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error('Request failed with status ' + response.status);
            }
            const geojson = await response.json();
            console.log('Geo layer ' + url + ' was loaded');
            L.geoJSON(geojson).addTo(map);
        } catch (error) {
            console.error('Error loading geo layer ' + url + ':', error);
        }
    };
    </script>
    ";

    return $output.$script;
}

Clickfwd\Hook\Filter::add('after_filter_output_module_maps_index', 'add_geo_layers_to_map_module', 10);

Check the module map

Open the listing detail page. The routes and shapes from the published GPX, KML, and GeoJSON attachments should appear on the module map. If the page also has a listing detail map, confirm that this listener does not add the same layers there.

The filter checks each published attachment with the legacy download permission before adding its URL. Check as a permitted visitor and as a guest denied download access. To deny access, open Browse > Media in the JReviews admin, edit the attachment, and set its Access level. Denied or unpublished attachments must not appear in the page's layer URLs. The visitor's browser requests each layer URL from your site, and MapsPro reads the file from your attachment storage. If a shape does not appear, open the browser's developer tools and check Console and Network for failed requests to maps/geojson or invalid-file errors. Keep JReviews' normal map scripts enabled. This example uses the map library's default shape appearance and does not move or zoom the map to show distant shapes.

Learn more