Skip to content

<ScriptGoogleMapsGeoJson> component #655

@DamianGlowala

Description

@DamianGlowala

🆒 Your use case

I'd like to use a Google Maps SFC to add GeoJSON to the map and apply some styles to it.

🆕 The solution you'd like

That's what I came up with so far:

<script setup lang="ts">
import { watch } from 'vue'
import { useGoogleMapsResource } from './useGoogleMapsResource'

const props = defineProps<{
  src: string | object
  style?: google.maps.Data.StylingFunction | google.maps.Data.StyleOptions
}>()

function addOrLoadGeoJson(geoJson: string | object, layer: google.maps.Data) {
  if (typeof geoJson === 'string') {
    layer.loadGeoJson(geoJson)
  }
  else {
    layer.addGeoJson(geoJson)
  }
}

const dataLayer = useGoogleMapsResource<google.maps.Data>({
  async create({ mapsApi, map }) {
    const layer = new mapsApi.Data({ map })

    layer.setStyle(props.style)

    addOrLoadGeoJson(props.src, layer)

    return layer
  },
  cleanup(layer) {
    layer.setMap(null)
  },
})

watch(() => props.src, (src) => {
  dataLayer.value.forEach(feature => dataLayer.value.remove(feature))

  addOrLoadGeoJson(src, dataLayer.value)
})

watch(() => props.style, (style) => {
  dataLayer.value.setStyle(style)
}, { deep: true })
</script>

<template>
</template>

🔍 Alternatives you've considered

No response

ℹ️ Additional info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions