I want to add text on the center of polygon feature in maps. I was referred to the this issue. and I made code like that.
<template>
<l-map style="height: 350px" :zoom="zoom" :center="center">
<l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
<l-polygon :lat-lngs="polygon.latlngs" :color="polygon.color">
<l-marker
:lat-lngs="polygonCenter(polygon.latlngs)"
:icon="polyGonText"
></l-marker>
</l-polygon>
</l-map>
</template>
<script>
import { LMap, LTileLayer, LPolygon, LMarker } from "vue2-leaflet";
import L from "leaflet";
export default {
components: {
LMap,
LTileLayer,
LPolygon,
LMarker,
},
data() {
return {
url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
attribution:
'© <a target="_blank" href="http://osm.org/copyright">OpenStreetMap</a> contributors',
zoom: 8,
center: [47.31322, -1.319482],
polygon: {
latlngs: [
[47.2263299, -1.6222],
[47.21024000000001, -1.6270065],
[47.1969447, -1.6136169],
[47.18527929999999, -1.6143036],
[47.1794457, -1.6098404],
[47.1775788, -1.5985107],
[47.1676598, -1.5753365],
[47.1593731, -1.5521622],
[47.1593731, -1.5319061],
[47.1722111, -1.5143967],
[47.1960115, -1.4841843],
[47.2095404, -1.4848709],
[47.2291277, -1.4683914],
[47.2533687, -1.5116501],
[47.2577961, -1.5531921],
[47.26828069, -1.5621185],
[47.2657179, -1.589241],
[47.2589612, -1.6204834],
[47.237287, -1.6266632],
[47.2263299, -1.6222],
],
color: "green",
},
};
},
methods: {
polygonCenter(latlngs) {
return L.polygon(latlngs).getBounds().getCenter();
},
polyGonText() {
return L.divIcon({ html: "No.1" });
},
},
mounted: function () {
this.polygon
.bindTooltip("My Text", { permanent: true, direction: "center" })
.openTooltip();
},
};
</script>
<style>
</style>
my code is referred to vue-leaflet site, and just add methods to get center of polygon "latLang" and set html object. But html text(No.1) is not shown on the polygon. How can I add text in to the polygon? Does anyone help me?
CodePudding user response:
You can attach text to a polygon using tooltip, like this:
polygon.bindTooltip("My Text",
{permanent: true, direction:"center"}
).openTooltip()
Edit:
I looked at your code and you're attaching bindTooltip() and openTooltop() functions to an object, this is incorrect. What you need to do is to attach these functions to an Leaflet mapObject.
Here's the code you need to update:
//template
<l-polygon ref="poly" :lat-lngs="polygon.latlngs" :color="polygon.color">
//mounted
mounted: function () {
this.$nextTick(() => {
const poly = this.$refs.poly.mapObject;
poly.bindTooltip("My Text", { permanent: true, direction: "center" }).openTooltip();
});
Also you should really use pure leaflet library, if you learn it once you'll be able to use it everywhere, does not matter if it is react, vue or pure js.
