Example: Multiple Markers Google Maps

#Example #GoogleMaps #MultipleMarkers #MarkerClustering #CustomControls #HtmlComponent #APIKey #security


Demonstrates

The code in the HtmlComponent is based on Google’s map example code and was modified for messaging with the web site page.

Replace the string GOOGLE_MAP_API_KEY in the HtmlComponent code with your own API key. See the forum post Secure a Google Maps API key in an HtmlComponent for details on how to protect your API key.

15 Likes

Really nice sample

Hi Yisrael

This looks just like what I think I’ll need!

Every time I think I’m getting to the ‘finished’ part of my website, something else just pops up!

I can’t seem to get the map to show however? It just displays a white square. This is what I’ve got from your example. Would you know where am I going wrong?

Back end file:

import wixData from 'wix-data';
export function getLocations() {
	return wixData.query("properties") // the database to query is 'properties'
		.find()
		.then((results) => {
			return results.items; // items is an array of locations from the collection
		})
		.catch((err) => {
			let errorMsg = err;
		});
}

Page code:

import {getLocations} from 'backend/locations';

$w.onReady(function () {
    sendLocations();
	$w("#html1").onMessage( (event) => {
		if(event.data === 'hello') {
			sendLocations();
		}
		else {
			$w('#text127').text = "Currently Veiwing: " + 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.price, position: {lat: loc.latitude, lng: loc.longitude}}); // wanted property price as title	
		}
		$w('#html1').postMessage({markers});
	});
}

In my html code: With swapped code (just swapped out for purpose of post)

<html>
<head>
    <title>Wix Code / Google Maps :: Multiple Markers</title>
</head>
<body>
    <div id="map" style="height: 100%; width: 100%;" />
    <script type="text/javascript">
        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,
                        center: {lat: 41.38506389999999, lng: 2.1734035}    // Barcelona is a good center point
                    });

                    // Add the markers to the map.
                    // Note: The code uses the JavaScript Array.prototype.map() method to
                    // create an array of markers based on a given "locations" array.
                    // The map() method here has nothing to do with the Google Maps API.
                    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 a marker clusterer to manage the markers.
                    var markerCluster = new MarkerClusterer(map, markers,
                        { gridSize: 20, maxZoom: 3, imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
                }
            }
        }
    </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=MY-CODE-PASTED-HERE&callback=init">
    </script>
</body>
</html>

All it’s displaying however is white box (even in preview mode)

Many thanks for any help! (again)

Thomas :slight_smile:

Hey, how come you event.data.markers is there actually markers? Try console.log that, I think you must use only event.data and not markers also.

Hey Thomas,

Sorry, I don’t see anything wrong. If the example works in your editor, then it should just be a matter of using the same parts in your project. Can’t get any more helpful than a working example. Make sure the database is set up properly by exporting from the example and then importing to your project. Perhaps there’s a problem with your API key?

Did you look at the browser’s Javascript console? Any error messages?

@Andreas - the line of code from my example uses .markers:
locations = event.data.markers;

Yisrael

@Yisrael-wix : Instead of using the html iFrame, is there a way to utilize this same functionality using the Google Maps App that you have in the Contacts Tab in the Wix Editor? The iFrame is buggy sometimes. Just curious. Lastly, is there a way to “stretch” the iframe so that it auto formats to the page width, like with the other Google Maps App in the Editor?

Hi Yisrael

All sorted. Great example! :slight_smile: it was an issue with the Key, it wasn’t registered in use.

Just a quicky: How would I remove the ‘on-hover’ box on the map itself?

I’m still wanting to use the below section (as a reference ID number to alter other items on the page) but I don’t want the ID number hovering above the marker as people move around the map.

//import {getLocations} from 'backend/locations';

//$w.onReady(function () {
//    sendLocations();
//	$w("html1").onMessage( (event) => {
//		if(event.data === 'hello') {
//			sendLocations();
//		}
//		else {
			*** $w('#text127').text = "Currently Veiwing: " + event.data;***
//		}
//	} );
//});

Many thanks, again!

Thomas :slight_smile:

WOW…Thanks Yisrael… I was just looking for some example like this… :slight_smile:

Hi Thomas,

I don’t really understand the code that you posted. If you want to get rid of the info windows, just delete the mouseover and mouseout event listeners. See the Google Maps API docs for more details on the code.

Yisrael

Hi Yisrael

All sorted and many thanks, fantastic example!

Just tested it with some practice properties and this is what came of it:

Thanks again!

Thomas

I need help writing code to hooks I have membership to the gym, which have a subscription start date and end date, I want the code to test whether the customer has active subscription or not, for example if the current date is equal to the date first and end, then write in the status field Yes, and if not in the range will write no.
Thanks!!

Hi,
Trying to enlarge the zoom, but get no change from zoom around 12.
Maybe it’s the largest zoom for Israel, but it’s not enough for my map.
Any idea??
Many thanks:)

Hey Dafna,

How are you?

How big of a zoom do you need? You want to show someone sitting in a lounge chair in the backyard? :upside_down_face:

Sorry, but I really have no idea about the zoom. I played around some with the zoom when I created the example, but didn’t really try to determine the full behavior. I remember that I was able to zoom pretty big. Google provides some examples that the user can play around with right on the Google site. Did you try playing around with those.

What about the built-in Wix GoogleMap component? Does it zoom OK there? If so, then it must be possible.

Good luck,

Yisrael

Hi Yisrael,

1st, many thanks for your reply:)
This is the map:
https://leitersbelz.wixsite.com/leiters-prototype/home
The zoom is currently 19, and it looks same as zoom 12.
What else can be done? Found it controlled only by the ‘zoom’ property…

Thanks a lot!
Dafna

Dafna,

Interesting - it’s possible to zoom with the zoom control on the map. I’ve really got no idea why the zoom can’t be set as the display default. Very strange. I would say it’s really a question for Google. Do they have a forum or a help page?

Yisrael

If you use styling that’s where to set that level.

Will check! thanks:)

So, when putting zoom on map constructor I get no response, and when adding it to the map css it enlarges everything, including the infowindows. All examples I found put it in the constructor, so I wonder why it doesn’t work for me

This is the code. very standard, but the zoom & center doesn’t respond:

var map = new google.maps.Map(document.getElementById(‘map’), {
zoom: 10,
center: {lat: 32.084639, lng: 34.872589},
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [
{

You actually have the latitude with tick marks:
center: {lat: ‘32.084639’, lng: 34.872589},
However, even when I fixed it, the zoom and center still doesn’t work.

Perhaps there’s some other problem with the HTML code.