<template>
<div id="app">
<h1></h1>
<button @click="setCenter">
目前位置: ,
</button>
g-map sdk上有
<map
:center.sync="center"
:map-type-id.sync="terrian"
:zoom.sync="18" >
<marker
v-for="m in markers"
:position.sync="m.position">
</marker>
</map>
</div>
</template>
<script>
import{ Map, Marker, load} from 'vue-google-maps'
import firebase from 'firebase'
// API key
load('你的 map api key');
var config = {
apiKey: "xxxxxx",
authDomain: "xxxxxx",
databaseURL: "xxxxx",
stroageBucket: "xxxxxx",
};
firebase.initializeApp(config);
export default {
components: {
Map, Marker
},
data () {
return {
msg: 'Hello ikea!',
center: {
lat: 0,
lng: 0
},
// 位置data
position: {
lat: 0,
lng: 0
},
mapId: '',
userId: '',
markers: []
}
},
// ready:
ready () {
// get mapID
this.mapId = location.hash.slice(1)
if (this.mapId === '') {
this.mapId = firebase.database().ref('/maps/').push().key
location.hash = this.mapId
}
// get userID
this.userId = localStorage.getItem('fire-geo-userId')
if (!this.userId) {
localStorage.setItem('fire-geo-userId', this.userId)
this.userId = firebase.database().ref('/maps/' + this.mapId).push().key
}
// bable 語法
const ref = firebase.database().ref(`/maps/$(this.mapId)/`)
ref.on('child_added', (data) => {
const marker = data.val()
this.markers.push({
key: data.key,
position: data.val().position
})
})
ref.on('child_changed', (data) => {
let marker = this.markers.find((m) => m.key === data.key)
marker.position = data.val().position
})
navigator.geolocation.watchPosition((position) => {
this.position.lat = position.coords.latitude
this.position.lng = position.coords.longitude
ref.child(this.userId).set({
position: this.position
})
})
},
methods:{
setCenter(){
this.center = this.position
}
}
</script>
<style>
body {
font-family: Helvetica, sans-serif;
}
map {
display: block;
width: 100%;
height: 500px;
}
</style>