Merge branch 'feat/refactor_map_component' into 'master'

Improve map component

See merge request les/gancio!28
This commit is contained in:
les 2023-05-09 16:49:07 +00:00
commit 4d781752a2
7 changed files with 183 additions and 221 deletions

View file

@ -0,0 +1,65 @@
<template lang="pug">
v-card
v-container
div(:style="{'height': mapHeight}")
Map.mt-4(:place='event.place' :height='mapHeight' )
v-row.my-4.d-flex.flex-column.align-center.text-center
.text-h6
v-icon(v-text='mdiMapMarker' )
nuxt-link.ml-2.text-decoration-none(v-text="event.place.name" :to='`/place/${event.place.name}`')
.mx-2(v-text="`${event.place.address}`")
v-card-actions
v-row(color='primary')
//- p.my-4(v-text="$t('common.getting_there')")
v-btn.ml-2(icon large :href="routeBy('foot')")
v-icon(v-text='mdiWalk')
v-btn.ml-2(icon large :href="routeBy('bike')")
v-icon(v-text='mdiBike')
v-btn.ml-2(icon large :href="routeBy('car')")
v-icon(v-text='mdiCar')
v-spacer
v-btn(@click='$emit("close")' outlined) Close
</template>
<script>
import { mapActions } from 'vuex'
import { mdiWalk, mdiBike, mdiCar, mdiMapMarker } from '@mdi/js'
export default {
components: {
[process.client && 'Map']: () => import('@/components/Map.vue')
},
data () {
return {
mdiWalk, mdiBike, mdiCar, mdiMapMarker,
mapHeight: "55vh"
}
},
props: {
event: { type: Object, default: () => ({}) }
},
methods: {
...mapActions(['setSetting']),
// mountLocateControl() {
// this.$refs.map.mapObject.locate({
// locateOptions: {
// maxZoom: 10
// }
// });
// this.$refs.map.mapObject.MyLocate();
// },
routeBy (type) {
const lat = this.event.place.latitude
const lon = this.event.place.longitude
const routingType = {
foot: "engine=fossgis_osrm_foot",
bike: "engine=fossgis_osrm_bike",
transit: null,
car: "engine=fossgis_osrm_car"
}
return `https://www.openstreetmap.org/directions?from=&to=${lat},${lon}&${routingType[type]}#map=14/${lat}/${lon}`
},
}
}
</script>

View file

@ -1,43 +1,28 @@
<template lang="pug">
client-only(placeholder='Loading...' )
v-card
v-container
LMap(ref="map"
id="leaflet-map-dialog"
:zoom="zoom"
:options="{attributionControl: false}"
:center="center")
LControlAttribution(position='bottomright' prefix="")
LTileLayer(
:url="url"
:attribution="attribution")
LMarker(
:lat-lng="marker.coordinates")
LMap(ref="leafletMap"
id="leaflet-map"
:style="{ 'height': height }"
:zoom="zoom"
:options="{attributionControl: false}"
:center="center")
LControlAttribution(position='bottomright' prefix="")
LTileLayer(
@tileload="$emit('tileload')"
@tileerror="$emit('tileerror')"
:url="url"
:attribution="attribution")
LMarker(v-if="showMarker"
:lat-lng="marker.coordinates"
@update:lat-lng="updateCoords"
:draggable="draggable")
v-row.my-4.d-flex.flex-column.align-center.text-center
.text-h6
v-icon(v-text='mdiMapMarker' )
nuxt-link.ml-2.text-decoration-none(v-text="event.place.name" :to='`/place/${event.place.name}`')
.mx-2(v-text="`${event.place.address}`")
v-card-actions
v-row
//- p.my-4(v-text="$t('common.getting_there')")
v-btn.ml-2(icon large :href="routeBy('foot')")
v-icon(v-text='mdiWalk')
v-btn.ml-2(icon large :href="routeBy('bike')")
v-icon(v-text='mdiBike')
v-btn.ml-2(icon large :href="routeBy('car')")
v-icon(v-text='mdiCar')
v-spacer
v-btn(@click='$emit("close")' outlined) Close
</template>
<script>
import "leaflet/dist/leaflet.css"
import { LMap, LTileLayer, LMarker, LPopup, LControlAttribution } from 'vue2-leaflet'
import { mapActions, mapState } from 'vuex'
import { Icon } from 'leaflet'
import { mdiWalk, mdiBike, mdiCar, mdiMapMarker } from '@mdi/js'
export default {
components: {
@ -49,20 +34,34 @@ export default {
},
data ({ $store }) {
return {
mdiWalk, mdiBike, mdiCar, mdiMapMarker,
url: $store.state.settings.tilelayer_provider || 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
attribution: $store.state.settings.tilelayer_provider_attribution || "<a target=\"_blank\" href=\"http://osm.org/copyright\">OpenStreetMap</a> contributors",
zoom: 14,
center: [this.event.place.latitude, this.event.place.longitude],
marker: {
address: this.event.place.address,
coordinates: {lat: this.event.place.latitude, lon: this.event.place.longitude}
},
routingProvider: 'openstreetmap',
}
},
computed: {
center () {
if (this.mapCenter.length)
return this.mapCenter
else {
this.place.latitude = isNaN(this.place.latitude) ? 0 : this.place.latitude
this.place.longitude = isNaN(this.place.longitude) ? 0 : this.place.longitude
return [this.place.latitude, this.place.longitude]
}
},
marker () {
return {
address: this.place.address,
coordinates: {lat: this.place.latitude, lon: this.place.longitude }
}
}
},
props: {
event: { type: Object, default: () => ({}) }
place: { type: Object, default: () => ({ latitude: 0, longitude: 0 }) },
height: { type: String, default: '' },
showMarker: { type: Boolean, default: true },
mapCenter: { type: Array, default: () => ([]) },
zoom: { type: Number, default: () => (16) },
draggable: { type: Boolean, default: false },
},
mounted() {
delete Icon.Default.prototype._getIconUrl;
@ -73,41 +72,23 @@ export default {
});
setTimeout(() => {
this.$refs.map.mapObject.invalidateSize();
if (this.$refs.leafletMap && this.$refs.leafletMap.mapObject ) {
this.$refs.leafletMap.mapObject.invalidateSize();
}
}, 200);
},
computed: {
...mapState(['settings']),
},
methods: {
...mapActions(['setSetting']),
// mountLocateControl() {
// this.$refs.map.mapObject.locate({
// locateOptions: {
// maxZoom: 10
// }
// });
// this.$refs.map.mapObject.MyLocate();
// },
routeBy (type) {
const lat = this.event.place.latitude
const lon = this.event.place.longitude
const routingType = {
foot: "engine=fossgis_osrm_foot",
bike: "engine=fossgis_osrm_bike",
transit: null,
car: "engine=fossgis_osrm_car"
}
return `https://www.openstreetmap.org/directions?from=&to=${lat},${lon}&${routingType[type]}#map=14/${lat}/${lon}`
},
updateCoords(v) {
this.place.latitude = Number.parseFloat(v.lat).toFixed(7)
this.place.longitude = Number.parseFloat(v.lng).toFixed(7)
}
}
}
</script>
<style>
#leaflet-map-dialog {
height: 55vh;
width: 100%;
#leaflet-map {
height: 10rem;
border-radius: .3rem;
border: 1px solid #fff;
z-index: 1;

View file

@ -1,77 +0,0 @@
<template lang="pug">
client-only(placeholder='Loading...' )
LMap(ref="mapEdit"
id="leaflet-map"
:zoom="zoom"
:options="{attributionControl: false}"
:center="center")
LControlAttribution(position='bottomright' prefix="")
LTileLayer(
:url="url"
:attribution="attribution")
LMarker(
:lat-lng="marker.coordinates")
</template>
<script>
import "leaflet/dist/leaflet.css"
import { LMap, LTileLayer, LMarker, LPopup, LControlAttribution } from 'vue2-leaflet'
import { Icon } from 'leaflet'
import { mdiWalk, mdiBike, mdiCar, mdiMapMarker } from '@mdi/js'
export default {
components: {
LMap,
LTileLayer,
LMarker,
LPopup,
LControlAttribution
},
data ({ $store }) {
return {
mdiWalk, mdiBike, mdiCar, mdiMapMarker,
url: $store.state.settings.tilelayer_provider || 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
attribution: $store.state.settings.tilelayer_provider_attribution || "<a target=\"_blank\" href=\"http://osm.org/copyright\">OpenStreetMap</a> contributors",
zoom: 16,
}
},
computed: {
center () {
return [this.place.latitude, this.place.longitude]
},
marker () {
return {
address: this.place.address,
coordinates: {lat: this.place.latitude, lon: this.place.longitude }
}
}
},
props: {
place: { type: Object, default: () => ({ latitude: 0, longitude: 0 }) }
},
mounted() {
delete Icon.Default.prototype._getIconUrl;
Icon.Default.mergeOptions({
iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
iconUrl: require('leaflet/dist/images/marker-icon.png'),
shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
});
setTimeout(() => {
if (this.$refs.mapEdit && this.$refs.mapEdit.mapObject ) {
this.$refs.mapEdit.mapObject.invalidateSize();
}
}, 200);
}
}
</script>
<style>
#leaflet-map {
height: 10rem;
border-radius: .3rem;
border: 1px solid #fff;
z-index: 1;
}
</style>

View file

@ -38,7 +38,8 @@ v-card
:rules="$validators.longitude")
p.mt-4(v-if='place.isNew' v-html="$t('event.address_geocoded_disclaimer')")
MapEdit.mt-4(:place='place' v-if="(settings.allow_geolocation && place.name !== 'online' && place.latitude && place.longitude)" )
Map.mt-4(:place='place' draggable=true
v-if="(settings.allow_geolocation && place.name !== 'online' && place.latitude && place.longitude)" )
v-divider(v-if='settings.allow_online_event && showGeocoded')
@ -76,7 +77,7 @@ export default {
onlineLocations: { type: Array, default: [] }
},
components: {
[process.client && 'MapEdit']: () => import('@/components/MapEdit.vue')
[process.client && 'Map']: () => import('@/components/Map.vue')
},
data ({$store}) {
return {

View file

@ -6,7 +6,7 @@ v-card
v-form
v-row
v-col(md=3)
v-col(cols=12 md=3)
v-autocomplete.mb-4(v-model='geocoding_provider_type'
@blur="save('geocoding_provider_type', geocoding_provider_type )"
:label="$t('admin.geocoding_provider_type')"
@ -15,7 +15,7 @@ v-card
:items="geocoding_provider_type_items"
:placeholder="geocoding_provider_type_default")
v-col(md=5)
v-col(cols=12 md=5)
v-text-field.mb-4(v-model='geocoding_provider'
@blur="save('geocoding_provider', geocoding_provider )"
:label="$t('admin.geocoding_provider')"
@ -23,7 +23,7 @@ v-card
persistent-hint
:placeholder="geocoding_provider_default")
v-col(md=4)
v-col(cols=12 md=4)
v-autocomplete.mb-6(v-model="geocoding_countrycodes" :disabled="!(geocoding_provider_type === null || geocoding_provider_type === 'Nominatim')"
:append-icon='mdiChevronDown'
@blur="save('geocoding_countrycodes', geocoding_countrycodes )"
@ -35,7 +35,7 @@ v-card
:hint="$t('admin.geocoding_countrycodes_help')")
v-row
v-col(md=6)
v-col(cols=12 md=6)
v-text-field.mb-4(v-model='tilelayer_provider'
@blur="save('tilelayer_provider', tilelayer_provider )"
:label="$t('admin.tilelayer_provider')"
@ -43,39 +43,44 @@ v-card
persistent-hint
:placeholder="tilelayer_provider_default")
v-col(md=6)
v-col(cols=12 md=6)
v-text-field(v-model='tilelayer_provider_attribution'
@blur="save('tilelayer_provider_attribution', tilelayer_provider_attribution )"
:label="$t('admin.tilelayer_provider_attribution')"
:placeholder="tilelayer_provider_attribution_default")
div(id="leaflet-map-preview" max-height='10px')
//- Map
Map(:key='mapKey' v-if='mapPreview'
@tileerror='tilelayerTestError'
@tileload='tilelayerTestSuccess'
height="20rem"
showMarker=false
:mapCenter='mapCenter'
:zoom='10')
v-card-actions
v-spacer
v-btn(color='primary' @click='testGeocodingProvider' :loading='testGeocodingLoading' outlined ) {{$t('admin.geocoding_test_button')}}
v-btn(color='primary' @click='testTileLayerProvider' :loading='testTileLayerLoading' outlined ) {{$t('admin.tilelayer_test_button')}}
v-btn(color='primary' @click='testGeocodingProvider' :loading='isNewGeocodingTest' outlined ) {{$t('admin.geocoding_test_button')}}
v-btn(color='primary' @click='testTileLayerProvider' :loading='isNewTilelayerTest' outlined ) {{$t('admin.tilelayer_test_button')}}
</template>
<script>
import { mapActions, mapState } from 'vuex'
import { isoCountries } from '../../server/helpers/geolocation/isoCountries'
import geolocation from '../../server/helpers/geolocation/index'
import { mdiChevronDown } from '@mdi/js'
// import Map from '~/components/Map'
import "leaflet/dist/leaflet.css"
export default {
props: {
setup: { type: Boolean, default: false }
components: {
[process.client && 'Map']: () => import('@/components/Map.vue')
},
// components: { Map },
data ({ $store }) {
return {
mdiChevronDown,
loading: false,
testGeocodingLoading: false,
testTileLayerLoading: false,
mapKey: 0,
mapPreview: false,
mapCenter: [42, 42],
isNewTilelayerTest: false,
isNewGeocodingTest: false,
geocoding_provider_type_items: ['Nominatim', 'Photon'],
geocoding_provider_type: $store.state.settings.geocoding_provider_type || '',
geocoding_provider_type_default: 'Nominatim',
@ -87,58 +92,39 @@ export default {
tilelayer_provider_attribution: $store.state.settings.tilelayer_provider_attribution || '',
tilelayer_provider_attribution_default: '<a target=\'_blank\' href=\"http://osm.org/copyright\">OpenStreetMap</a> contributors',
countries: isoCountries,
mapPreviewTest: null,
}
},
created() {
if (process.client) {
const L = require('leaflet')
computed: {
...mapState(['settings', 'events']),
tilelayerTest() {
const v = this.tilelayer_provider !== '' ? this.tilelayer_provider : this.tilelayer_provider_default
return v
},
geocodingTest() {
const v = this.geocoding_provider !== '' ? this.geocoding_provider : this.geocoding_provider_default
return v
}
},
computed: mapState(['settings', 'events']),
methods: {
...mapActions(['setSetting']),
async testGeocodingProvider () {
this.testGeocodingLoading = true
const geocodingProviderTest = this.geocoding_provider || this.geocoding_provider_default
const geocodingSoftwareTest = this.geocoding_provider_type || this.geocoding_provider_type_default
const geocodingQuery = 'building'
this.isNewGeocodingTest = true
const currentGeocodingProvider = geolocation.getGeocodingProvider(this.settings.geocoding_provider_type)
// random query
const geocodingQuery = Math.random().toString(36).slice(2, 7);
try {
if (geocodingSoftwareTest === 'Nominatim') {
const geolocation = await this.$axios.$get(`${geocodingProviderTest}`, {timeout: 3000, params: {q: `${geocodingQuery}`, format: 'json', limit: 1 }} )
} else if (geocodingSoftwareTest === 'Photon') {
const geolocation = await this.$axios.$get(`${geocodingProviderTest}`, {timeout: 3000, params: {q: `${geocodingQuery}`, limit: 1}} )
}
this.$root.$message(this.$t('admin.geocoding_test_success', { service_name: geocodingProviderTest }), { color: 'success' })
const ret = await this.$axios.$get(`placeOSM/${currentGeocodingProvider.commonName}/${geocodingQuery}`, { timeout: 3000 })
const res = currentGeocodingProvider.mapQueryResults(ret)
this.geocodingTestSuccess()
} catch (e) {
this.$root.$message(this.$t('admin.tilelayer_test_error', { service_name: geocodingProviderTest }), { color: 'error' })
this.geocodingTestError()
}
this.testGeocodingLoading = false
this.isNewGeocodingTest = false
},
async testTileLayerProvider () {
this.testTileLayerLoading = true
const tileThis = this
const tileLayerTest = this.tilelayer_provider || this.tilelayer_provider_default
const tileLayerAttributionTest = this.tilelayer_provider_attribution || this.tilelayer_provider_attribution_default
// init tilelayer
if (this.mapPreviewTest == null) {
this.mapPreviewTest = L.map("leaflet-map-preview").setView([40,40],10);
}
this.tileLayer = L.tileLayer(`${tileLayerTest}`, {attribution: `${tileLayerAttributionTest}`})
this.tileLayer.addTo(this.mapPreviewTest)
// tilelayer events inherited from gridlayer https://leafletjs.com/reference.html#gridlayer
this.tileLayer.on('tileload', function (event) {
tileThis.tileLayerTestSucess(event, tileLayerTest)
});
this.tileLayer.on('tileerror', function(error, tile) {
tileThis.tileLayerTestError(event, tileLayerTest)
tileThis.tileLayer = null
});
this.testTileLayerLoading = false
testTileLayerProvider () {
this.isNewTilelayerTest = true
this.mapPreview = true
this.mapKey++
},
save (key, value) {
if (this.settings[key] !== value) {
@ -148,22 +134,25 @@ export default {
done () {
this.$emit('close')
},
geocodingTestError(event, tileLayerTest) {
this.$root.$message(this.$t('admin.geocoding_test_error', { service_name: geocodingTest }), { color: 'error' })
handleMsg(t, s, c) {
this.$root.$message(this.$t(t, { service_name: s }), { color: c })
},
tileLayerTestSucess(event, tileLayerTest) {
this.$root.$message(this.$t('admin.tilelayer_test_success', { service_name: tileLayerTest }), { color: 'success' })
geocodingTestError() {
this.handleMsg('admin.geocoding_test_error', this.geocodingTest, 'error')
},
tileLayerTestError(event, tileLayerTest) {
this.$root.$message(this.$t('admin.tilelayer_test_error', { service_name: tileLayerTest }), { color: 'error' })
geocodingTestSuccess() {
this.handleMsg('admin.geocoding_test_success', this.geocodingTest, 'success')
},
tilelayerTestError() {
this.isNewTilelayerTest && this.handleMsg('admin.tilelayer_test_error', this.tilelayerTest, 'error')
this.isNewTilelayerTest = false
},
tilelayerTestSuccess() {
this.isNewTilelayerTest && this.handleMsg('admin.tilelayer_test_success', this.tilelayerTest, 'success')
this.isNewTilelayerTest = false
}
}
}
</script>
<style>
#leaflet-map-preview {
height: 20rem;
}
</style>

View file

@ -62,7 +62,8 @@ v-container
:label="$t('common.longitude')"
:rules="$validators.longitude")
MapEdit.mt-4(:place.sync='place' :key="dialog" v-if="settings.allow_geolocation && place.name !== 'online' && place.latitude && place.longitude")
Map.mt-4(:place.sync='place' :key="dialog" draggable=true
v-if="settings.allow_geolocation && place.name !== 'online' && place.latitude && place.longitude")
v-card-actions
v-spacer
@ -96,7 +97,7 @@ import geolocation from '../../server/helpers/geolocation/index'
export default {
components: {
[process.client && 'MapEdit']: () => import('@/components/MapEdit.vue')
[process.client && 'Map']: () => import('@/components/Map.vue')
},
data( {$store} ) {
return {
@ -109,7 +110,7 @@ export default {
addressList: [],
address: '',
search: '',
place: { name: '', address: '', id: null },
place: { name: '', address: '', latitude: 0, longitude: 0, id: null },
headers: [
{ value: 'name', text: this.$t('common.name') },
{ value: 'address', text: this.$t('common.address') },
@ -128,7 +129,8 @@ export default {
},
async fetch() {
this.places = await this.$axios.$get('/places')
this.places.splice(this.places.findIndex((p) => p.name === 'online' ), 1)
// do not allow edit the online place
this.places = this.places.filter(p => p.name !== 'online')
},
computed: {
...mapState(['settings']),

View file

@ -177,7 +177,7 @@ v-container#event.pa-2.pa-sm-2(itemscope itemtype="https://schema.org/Event" v-t
EmbedEvent(:event='event' @close='showEmbed=false')
v-dialog(v-show='settings.allow_geolocation && event.place.latitude && event.place.longitude' v-model='mapModal' :fullscreen='$vuetify.breakpoint.xsOnly' destroy-on-close)
Map(:event='event' @close='mapModal=false')
EventMapDialog(:event='event' @close='mapModal=false')
</template>
<script>
@ -188,6 +188,7 @@ import clipboard from '../../assets/clipboard'
import MyPicture from '~/components/MyPicture'
import EventAdmin from '@/components/eventAdmin'
import EmbedEvent from '@/components/embedEvent'
import EventMapDialog from '@/components/EventMapDialog'
const { htmlToText } = require('html-to-text')
@ -202,7 +203,7 @@ export default {
EventAdmin,
EmbedEvent,
MyPicture,
[process.client && 'Map']: () => import('@/components/Map.vue')
EventMapDialog
},
async asyncData ({ $axios, params, error }) {
try {