Geocoding Multiple Addresses to Google Maps

This is the closest I can get to what I need to do. I really don’t know how to code, but before I moved to Wix I was using the Google Maps api with a MySQL database. I was able to have a map with multiple markers populated from my database. I would like to replicate this with Wix, but I am pretty confused.

So far I have a blank map working within an HTML container with my API key. I have a database “Properties” that contains two different multifamily real-estate properties (just for testing, I have over 2,000 properties that I will import into the database). Within the Properties database I have the fields propertyName, latitude, and longitude. Those are the official js field keys.

I have tried to use your code, but since I am unfamiliar with the syntax of Javascript I am not sure what I need to replace or change to make it work with my database. I am also not sure if I need some additional backend code that you are not showing above.

Any suggestions or help would be much appreciated. If someone could point me in the right direction I might be able to figure this out. Thank you in advanced!

Hello Everyone, I am currently struggling with something very similar to this, David, did it finally work out correctly?

Hi All – Sorry for the delay responding on this.

I’ve pasted my current page code and HTML below. Essentially, you create an object array on the page, which in my case is “locations”, JSON it, then feed it into the HTML code. Presto! It should work.

async function mapItems (projItems2) {

	let itemsCount = projItems2.length;
				
	let locations = [];
	let requests = 0;
	for (var i = 0; i < itemsCount; i++) {
	requests++;			
		locations.push({
			"info": projItems2[i]["oppTitle"],
			"lat": projItems2[i]["lat"],
			"long":projItems2[i]["long"],
			"count": projItems2[i]["_id"],
		});
						
	if (requests === itemsCount) {
		let json_locations = JSON.stringify(locations);
		$w("#html2").postMessage(json_locations);						
	}

	}			
	
}
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Google Maps APIs</title>
	<script src="/path/to/markerwithlabel.js" type="text/javascript"></script>
	<link href="style.css" rel="stylesheet">


</head>

<body>

	<div id="map"></div>

	<script src="script.js"></script>
	<script async defer 
					src="https://maps.googleapis.com/maps/api/js?key=API KEY&callback=initMap"></script>
</body>

</html>

<style>

	html,
body {
	height: 100%;
	margin: 0;
	padding: 0;
}
#map {
	height: 100%;
}

	</style>

	<script>

var markersArray = [];			
			
window.onmessage = (event) => { 
    if (event.data) {
    	if (event.data === "clear") {
    		setMapOnAll(null);
    	} else {
        let receivedData = event.data
        let parsed_data = JSON.parse(receivedData);
        window.parent.postMessage("Test", "*");
        initMap(parsed_data);
    	} 
    }
};

 function initMap(receivedData) {
    
		var locations = receivedData;

	var map = new google.maps.Map(document.getElementById('map'), {
		zoom: 13,
		center: new google.maps.LatLng(35.223603, -80.836319),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});

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

	// var marker, i;
	
	// Upper Bound
	
	var markerIcon = {
	  url: 'http://image.flaticon.com/icons/svg/252/252025.svg',
	  scaledSize: new google.maps.Size(40, 40),
	  origin: new google.maps.Point(0, 0),
	  anchor: new google.maps.Point(32,65)
};

	var markerLabel = " "

	// Lower Bound

	for (i = 0; i < locations.length; i++) {
		marker = new google.maps.Marker({
			map: map,
			animation: google.maps.Animation.DROP,
			icon: markerIcon,
			position: new google.maps.LatLng(locations[i].lat, locations[i].long),			
			label: {
			    text: markerLabel,
			    fontSize: "16px",
    			fontWeight: "bold"
			  },
			labelAnchor: new google.maps.Point(18, 12),
  			labelClass: "my-custom-class-for-label"
		});
		markersArray.push(marker);
		google.maps.event.addListener(marker, 'click', (function (marker, i) {
			return function () {
				infowindow.setContent(locations[i].info);
				infowindow.open(map, marker);
				window.parent.postMessage(locations[i].count, "*");
			}
		})(marker, i));
	}
}

function setMapOnAll(map) {
        for (var i = 0; i < markersArray.length; i++) {
          markersArray[i].setMap(map);
        }
}

	</script>

Thank you for posting this. My database has over 2,000 locations. I am making progress! It only maps the items after I have queried the database to a smaller number like 100 locations. I am wondering if this is a Wix limitation as I had no problem mapping all locations before from MySQL database. Any thoughts??

Pretty sure there is a default limit to Wix data query, but you can modify it. Check Wix code api for query, should show it there. If not, you may have to loop your query and concatenation results, then map

Hi:)
Followig is my html component code for dynamic google map.
Need help with closing all infowindows except the clicked one.
Thanks a lot, Dafna
markersData.forEach((data)=> {
console.log("LENGTH: " + markersData.length);
let marker = new google.maps.Marker({
animation: google.maps.Animation.BOUNCE,
position: data.position,
icon: {
url: data.icon,
scaledSize: new google.maps.Size(40, 40)
},
title: data.title,
map: map
})
let info = new google.maps.InfoWindow({
content: data.content,
pixelOffset: new google.maps.Size(0, -10)
})
//(function(marker, data) {
google.maps.event.addListener(marker, “click”, function(e) {
info.setContent(data.content);
info.open(map, marker);
});
//})(marker, data);
})

Hi,
Will appreciate it very very much if someone can take a look at my init function.
The problem occures when clicking a marker, and then an infowindow is opened, and other infowindows stays open. Can’t figure out how to close previous infowindows:
page: https://www.wonderwix.net/google-map
Many manhy thanks!!!
Dafna:)

function init() {
window.onmessage = (event) => {
if (event.data) {
markersData = event.data.markersArr;

            var map = new google.maps.Map(document.getElementById('map'), { 
                	zoom: 13, 
	    	scale: 2, 
                	center: markersData[5].position, 
	    	mapTypeId: google.maps.MapTypeId.ROADMAP, 
		}); 

	var i; 
	for (i = 0; i < markersData.length; i++) { 
	    	console.log("LENGTH: " + markersData.length); 
                let marker = new google.maps.Marker({ 
                    	position: markersData[i].position, 
	                icon: { 
		                url: markersData[i].icon, 
		                scaledSize: new google.maps.Size(24, 32) 
		            	}, 
	                title: markersData[i].title, 
                     	map: map 
                    	}) 
	    	let info = new google.maps.InfoWindow({ 
	            	content: markersData[i].content, 
			pixelOffset: new google.maps.Size(0,0) 
            	        }) 

google.maps.event.addListener(marker, ‘click’, (function (marker, i) {
return function () {
var x;
for(x = 0; x < markersData.length; x++){
//info[x].close(); //doesn’t work
}
info.setContent(markersData[i].content);
info.open(map, marker);
}
})(marker, i));
}
}
}
}

David,

This is truly AMAZING work!! I THANK YOU infinitely for your constant detailed contributions! omg. You’ve helped me with all the sophisticated features I needed for my site (along with CODE QUEEN Nayeli AND Andreas Kviby). I can’t thank you enough. I wish everyone was as dedicated in the will to freely share, **follow up, and help others in the way you do. I also learned all my coding knowledge from Wix Code so your insight has been tremendously valuable and priceless. I highly admire your creative ingenuity and workaround solutions for all the missing pieces Wix Code has yet to deliver in an archived fashion. If everyone contributed in this way, Wix Code would be at a totally different level than it is today.

Despite the lack of Wix Code * archived (not just having to dig through the internet and forum constantly) and more advanced ‘sophisticated features’ as of yet (although they keep growing exponentially on on daily basis), it shows how strong, diverse, and intuitive the Wix Code foundation has been built. The Wix Code Team is also amazing. Liran always delivers, amongst many others, that help make this process much easier through their constant support.

**Once I am done, I am going to post all of the solutions I have documented for all of these advanced features so that other Wix Coders can also benefit from all of our endless trial and errors, and help avoid others going through the same lengthy problem solving process that we have struggled through victoriously.

I THANK YOU ALL!

  • Nelson

Hi guys. For those who made it to work the code of this topic, can you please post the link of your website? I’m not that sure that the code does what i want to do, so if u can please give me the link of your live version i can see how it looks and what it does.

Thank you so much.

Andrea- Israel
from Wix published an article in the tips and tricks section. Id recommend you check that out.

Andrea,

Here is the more recent code sample archive ttththat is being constructed where you cacan fiffind the same example in detail ttththat Yisrael kindlyposteposted. Omg THIS TTTYTYTYPTYPING GLITCH!!!
https://support.wix.com/en/article/index-of-wix-code-examples

Hope that elps.

-Nelson

Hello @david-seroy @jason-wadsworth @palombo-kevin @dafna-kotzer

I have followed through this code and since i am trying to implement the same thing, i am not sure where i am going wrong. please take some few minutes and let me know.

My Target
I want to query locations: tribe, latitude & Longitude from a collection called EasternAfrica and display on the google maps with on click action on the locations where it should load some page or collection.

Backend Code:

import wixData from ‘wix-data’ ;
export function getLocations() {
return wixData.query( “EasternAfrica” )
.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 () {
mapItems();
$w( “#html2” ).onMessage( (event) => {
if (event.data === ‘hello’ ) {
mapItems();
}
else {
//$w(‘#txtLocationClicked’).text = "Clicked on the Wix Office location: " + event.data;
}
} );
});

async function mapItems (projItems2) {

let itemsCount = projItems2.length;

let locations = ;
let requests = 0 ;
for ( var i = 0 ; i < itemsCount; i++) {
requests++;
locations.push({
“info” : projItems2[i][ “tribe” ],
“lat” : projItems2[i][ “latitude” ],
“long” :projItems2[i][ “longitude” ],
“count” : projItems2[i][ “_id” ],
});

if (requests === itemsCount) {
let json_locations = JSON.stringify(locations);
$w( “#html2” ).postMessage(json_locations);
}

}            

}

HTML CODE:

Google Maps APIs
<div id= "map" ></div> 

<script src= "script.js" ></script> 
<script  **async**  defer  
                src= "https://maps.googleapis.com/maps/api/js?key=AIzaSyCW4yYyApdHpWMfKjGUlN7Kja1gwGRyfRc&callback=initMap" ></script> 
html, body { height: 100 %; margin: 0 ; padding: 0 ; } #map { height: 100 %; }
<script> 

var markersArray = ;

window.onmessage = (event) => {
if (event.data) {
if (event.data === “clear” ) {
setMapOnAll( null );
} else {
let receivedData = event.data
let parsed_data = JSON.parse(receivedData);
window.parent.postMessage( “Test” , “*” );
initMap(parsed_data);
}
}
};

function initMap(receivedData) {

var locations = receivedData;

var map = new google.maps.Map(document.getElementById( ‘map’ ), {
zoom: 13 ,
center: new google.maps.LatLng( 35.223603 , - 80.836319 ),
mapTypeId: google.maps.MapTypeId.ROADMAP
});

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

// var marker, i;

// Upper Bound

var markerIcon = {
url: ‘http://image.flaticon.com/icons/svg/252/252025.svg’ ,
scaledSize: new google.maps.Size( 40 , 40 ),
origin: new google.maps.Point( 0 , 0 ),
anchor: new google.maps.Point( 32 , 65 )
};

var markerLabel = " "

// Lower Bound

for (i = 0 ; i < locations.length; i++) {
marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
icon: markerIcon,
position: new google.maps.LatLng(locations[i].lat, locations[i]. long ),
label: {
text: markerLabel,
fontSize: “16px” ,
fontWeight: “bold”
},
labelAnchor: new google.maps.Point( 18 , 12 ),
labelClass: “my-custom-class-for-label”
});
markersArray.push(marker);
google.maps.event.addListener(marker, ‘click’ , ( function (marker, i) {
return function () {
infowindow.setContent(locations[i].info);
infowindow.open(map, marker);
window.parent.postMessage(locations[i].count, “*” );
}
})(marker, i));
}
}

function setMapOnAll(map) {
for ( var i = 0 ; i < markersArray.length; i++) {
}
}

</script> 

I get only a preview of a blank google map

@David Seroy
@Jason Wadsworth
@Palombo Kevin
@Dafna Kotzer