Vorbly Code | WIX CODE GOOGLE MAPS CLUSTERS & MARKERS

Vorbly <Code>

CODING MADE EASY WITH VORBLY

WIX CODE GOOGLE MAPS CLUSTERS & MARKERS

Need a Google Map with multiple geolocation markers and clusters? This tutorial will show you how to add a Google Map with multiple markers and clusters from a Wix database. We will provide you with the webpage elements and sample codes required to implement this feature.

THE DEMO

1/6

THE ELEMENTS

The Page

HTML iframe: #html1 (embed Google Maps)

Text Element: #name (display location name)

Google Maps API Key

Go to Google Maps Developer and retrieve your API key.

Then search for "Maps JavaScript API" and enable it.

The Database

Create a database: Locations (dataset1)

Recommended fields:

  • Geolocation Latitude: latitude

  • Geolocation Longitude: longitude

  • Location Name: title

Tip: You can use Google Maps or other online tools to find the latitude and longitude of addresses.

Backend Web Module

Create a backend web module (locations.jsw).

THE CODE

Page Code

import {getLocations} from 'backend/locations';

 

$w.onReady(function () {

sendLocations();

    $w("#html1").onMessage( (event) => {

        if(event.data === 'hello') {

            sendLocations();

        }

        else {

            $w('#name').text = event.data;

        }

    } );

});

 

function sendLocations() {

    getLocations().then((locations) => {

        let markers = [];

        for (let i = 0; i < locations.length; i++) {

            let loc = locations[i];

            markers.push({title: loc.title, position: {lat: loc.latitude, lng: loc.longitude}});    

        }

        $w('#html1').postMessage({markers});

    });

}

HTML iframe

<html>

<head>

    <title>YOUR TITLE</title>

</head>

<body>

    <div id="map" style="height: 100%; width: 100%;" />

    <script type="text/javascript">

 

    let barcelona = {lat: 41.38506389999999, lng: 2.1734035}; // Re-center map at Barcelona, Spain //

 

       function RestoreControl(controlDiv, map) {

           

   // Set CSS for the control border //

            var controlUI = document.createElement('div');

            controlUI.style.backgroundColor = '#fff';

            controlUI.style.border = '2px solid #fff';

            controlUI.style.borderRadius = '3px';

            controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';

            controlUI.style.cursor = 'pointer';

            controlUI.style.marginBottom = '22px';

            controlUI.style.textAlign = 'center';

            controlUI.title = 'Click to reset the map';

            controlDiv.appendChild(controlUI);

 

            // Set CSS for the control interior //

            var controlText = document.createElement('div');

            controlText.style.color = 'rgb(25,25,25)';

            controlText.style.fontFamily = 'Helvetic Light,sans-serif';

            controlText.style.fontSize = '12px';

            controlText.style.lineHeight = '20px';

            controlText.style.paddingLeft = '5px';

            controlText.style.paddingRight = '5px';

            controlText.innerHTML = 'Restore Map';

            controlUI.appendChild(controlText);

 

            // Set the map to Barcelona, Spain //

            controlUI.addEventListener('click', function() {

                map.setCenter(barcelona);

                map.setZoom(2);

            });

        }

 

        let locations = null;

        function init() {

            if(locations === null) { // if no locations, let page know

                window.parent.postMessage("hello", "*");

            }

            window.onmessage = (event) => {

                if (event.data) {

                    locations = event.data.markers;

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

                    let map = new google.maps.Map(document.getElementById('map'), {

                        zoom: 2,

                        streetViewControl: false,

                        center: barcelona   //{lat: 41.38506389999999, lng: 2.1734035} // Set Barcelona, Spain as the center location //

                    });

 

                    // Adding markers to map. Create a markers array based on locations. //

                    var markers = locations.map(function (location) {

                        let marker = new google.maps.Marker({

                            position: location.position,

                            map: map

                        })

                        google.maps.event.addListener(marker, 'mouseover', (function (marker) {

                            return function () {

                                infowindow.setContent(location.title);

                                infowindow.open(map, marker);

                            }

                        })(marker));

                        google.maps.event.addListener(marker, 'mouseout', (function (marker) {

                            return function () {

                                infowindow.close();

                            }

                        })(marker));

                        google.maps.event.addListener(marker, 'click', (function (marker) {

                            window.parent.postMessage(location.title, "*");

                        }));

                        return marker;

                    });

 

                    // Add clusters to consolidate markers //

                    var markerCluster = new MarkerClusterer(map, markers,

                        { gridSize: 20, maxZoom: 3, imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });

 

                    // Create the DIV to hold the control and call CenterControl() function //

                    var restoreControlDiv = document.createElement('div');

                    var restoreControl = new RestoreControl(restoreControlDiv, map);

 

                    restoreControlDiv.index = 1;

                    map.controls[google.maps.ControlPosition.TOP_CENTER].push(restoreControlDiv);                       

                }

            }

        }

    </script>

    <script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">

    </script>   

    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR-GOOGLE-MAPS-API-KEY&callback=init">

    </script>

</body>

</html>

Back-End Code

// locations.jsw //

 

import wixData from 'wix-data';

export function getLocations() {

    return wixData.query("Locations")

        .find()

        .then((results) => {

            return results.items; // items is an array of locations from the collection

        })

        .catch((err) => {

            let errorMsg = err;

        });

}

COMMENTS

I'm a paragraph. Click here to add your own text and edit me. It's easy.

No comments. Be the first to leave a comment.

How could I change the code so that the maps centres on the users location?

Stuart

Sep 13, 2019

1

how can i use this marker clusterer but the cluster aint changing in every zoom level
thank you

Afridho Rachmadi K

Oct 21, 2019

1

Hi Stuart,

Thank you for leaving a comment!

Firstly, you will have to get the user's current geolocation. Please refer to the Google Maps JavaScript API below.

https://developers.google.com/maps/documentation/javascript/geolocation

Andrew (Vorbly)

Nov 02, 2019

0

Hi Afridho Rachmadi K,

The use case could be clusters of properties listed in a certain neighborhood or the number of UNESCO locations around the world. Depending on the area of interest, you can fine tune the zoom level of your map. I hope this answers your question. Thank you.

Andrew (Vorbly)

Nov 02, 2019

0

WEB DESIGN & DEVELOPMENT SOLUTIONS

GET PROFESSIONAL HELP