In a previous article, I’ve written how we can create a polygon using the Data Layer of the Google Maps JavaScript API. In this tutorial, we’ll have a look at how we can access or get the property of a data layer, like a polygon.
Here’s the example code to demonstrate the same:
<template>
<div>
<div id="data-layers-map" class="map-margins"></div>
</div>
</template>
<script>
import loadGoogleMapsApi from "load-google-maps-api";
import { gMapsApiKey } from "./../constants";
export default {
name: "DataFeatureIdOnClick",
data() {
return {
map: null,
};
},
mounted() {
loadGoogleMapsApi({
key: gMapsApiKey,
libraries: ["drawing", "geometry"],
}).then(async () => {
const mapZoom = 14;
const { google } = window;
const mapOptions = {
zoom: mapZoom,
mapTypeId: google.maps.MapTypeId.HYBRID,
center: new google.maps.LatLng({ lat: 23, lng: 57 }),
mapTypeControl: true,
streetViewControl: false,
mapTypeControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT,
},
};
this.map = new google.maps.Map(
document.getElementById("data-layers-map"),
mapOptions
);
const polygonCoords = [
{ lat: 28.4173106, lng: 77.0406078 },
{ lat: 28.4014569, lng: 77.0450281 },
{ lat: 28.406553, lng: 77.0587181 },
{ lat: 28.4208963, lng: 77.0517658 },
{ lat: 28.4173106, lng: 77.0406078 },
];
const tempBounds = new google.maps.LatLngBounds();
for (let j = 0; j < polygonCoords.length; j++) {
const x = {
lat: polygonCoords[j].lat,
lng: polygonCoords[j].lng,
};
const BoundLatLng = new google.maps.LatLng({
lat: parseFloat(x.lat),
lng: parseFloat(x.lng),
});
tempBounds.extend(BoundLatLng);
}
const centroid = tempBounds.getCenter();
this.map.data.add({
geometry: new google.maps.Data.Polygon([polygonCoords]),
properties: {
id: 0,
name: 'Sector 49'
},
});
this.map.data.addListener("click", function (event) {
if (event.feature.getGeometry().getType() === "Polygon") {
alert("Polygon Name: " + event.feature.getProperty("name"));
}
console.log(event.feature);
});
this.map.setCenter(centroid);
});
},
};
</script>
Code language: HTML, XML (xml)
In the code above, we’ve created a polygon as a data layer feature through lines 63-69. Then we’ve added an event listener to the feature through lines 71-76. We’ve accessed and shown the property value for ‘name’ in the alert dialog.
Here’s a working version of the above code: