I am usually using the ref keyword to access components within vue. But I seem to not have understood how I access HTML tags from within a component.
I tried:
<input type="text" ref="searchAddress" id="searchAddress" name="searchAddress" class="form-control" v-model="incidentForm.searchAddress">
and within the vue component:
var input = this.$refs.searchAddress;
but this does not work, so I assume it only works when referencing components? How do I access the input tag from within vue?
I created a class for managing all the GoogleMaps Api calls that will be included into my Vue files. Therefore I do not see a way, how I could handle accessing the data of a specific input field. What would be the right approach to avoid a direct access like this?
The full code example and being more specific:
The Autocomplete Function of GoogleMaps does not return anything as I would expect. Uncaught TypeError: Cannot set property 'autocompletePlace' of undefined. this.autocompletePlace = place seems to be not working.
methods: {
initMap: function initMap() {
this.initialLocation = this.createInitialLocation(48.184845, 11.252553);
this.mapSetup(this.$refs.map, this.initialLocation, function () {
this.initAutoCompleteListener(function (place) {
this.autocompletePlace = place;
});
}.bind(this));
}
}
GoogleMapsApi.js
export default {
data() {
return {
map: '',
currentIncidentLocation: '',
autocomplete: '',
searchMarker: ''
}
},
events: {
currentIncidentLocation: function(location) {
this.currentIncidentLocation = location;
}
},
methods: {
createInitialLocation: function(latitude, longitude) {
return new google.maps.LatLng(latitude, longitude);
},
mapSetup: function(selector, initialLocation, callback) {
this.map = new google.maps.Map(selector, {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
this.map.setCenter(initialLocation);
this.searchMarker = this.createMarker();
var input = document.getElementById('searchAddress');
this.autocomplete = new google.maps.places.Autocomplete(input);
callback();
},
initAutoCompleteListener: function(callback) {
this.autocomplete.addListener('place_changed', function() {
var place = this.autocomplete.getPlace();
if (!place.geometry) {
window.alert("Der Ort konnte nicht gefunden werden");
return;
}
callback(place);
}.bind(this));
},
createMarker: function() {
var marker = new google.maps.Marker({
map: this.map
})
return marker;
}
}
}
GISView.vue
<template>
<div ref="map" id="map" class="google-map" style="height: 800px; position: relative; overflow: hidden;">
</div>
</template>
<script>
import GoogleMaps from '../mixins/GoogleMaps.js';
export default {
mixins: [GoogleMaps],
data() {
return {
initialLocation: '',
autocompletePlace: ''
}
},
mounted() {
this.$events.$on("MapsAPILoaded", eventData => this.initMap());
},
methods: {
initMap: function() {
this.initialLocation = this.createInitialLocation(48.184845, 11.252553);
this.mapSetup(this.$refs.map, this.initialLocation, function() {
this.initAutoCompleteListener(function(place) {
this.autocompletePlace = place;
})
}.bind(this));
}
}
}
</script>
You bound the outer function, but not the inner one. Try
this.initAutoCompleteListener(function(place) {
this.autocompletePlace = place;
}.bind(this))
You can access HTML tags the same way using $refs, find below example:
<template>
<div class="example">
<input
type="text"
id="searchAddress"
name="searchAddress"
class="form-control"
ref="searchAddress"
placeholder="Input placeholder"
v-model="inputModel">
</div>
</template>
<script>
import Hello from './components/Hello'
export default {
name: 'app',
data() {
return {
inputModel: ''
}
},
mounted() {
const el = this.$refs.searchAddress
console.log('Ref to input element: ', el)
console.log('Placeholder attr from the ref element: ', el.placeholder) // logs "Input placeholder"
}
}
Related
I'm using Here Maps (Freemium plan) in a VueJs application that uses vue-router.
I made a Vue component for displaying a map which uses Routing to create an SVG path between 2 points following this articles:
https://developer.here.com/blog/showing-a-here-map-with-the-vue.js-javascript-framework
https://developer.here.com/documentation/map-image/dev_guide/topics/examples-routing-new-york-pois.html
I include Here Maps library ver 3.1 (CDN):
https://js.api.here.com/v3/3.1/mapsjs-service.js
https://js.api.here.com/v3/3.1/mapsjs-data.js
https://js.api.here.com/v3/3.1/mapsjs-ui.js
https://js.api.here.com/v3/3.1/mapsjs-mapevents.js
But the Vue component occasionally throws an error:
Uncaught (in promise) D {message: "H.map.DataModel#add (Argument #0 [object Object])"
The things I've noticed are:
If I reload the page sometimes it works fine and sometimes not
With certain route paths it works everytime
I've tried so hard to find the problem, no luck.
I think maybe it's the combination of vue-router and loading Here Maps library through CDN that causes this problem.
Is there a npm package for Here Maps out there?
Have you also experienced this issue?
Here is the code my map Vue component.
<template>
<div>
<div ref="map" class="here-map__map" />
</div>
</template>
<script>
export default {
data() {
return {
map: {},
coordinates: { lat: 46, lng: 12 },
platform: {},
waypoints: [],
markers: [],
icon: ''
}
},
props: {
property: {
zoom: 8,
markerIcon: "marker",
routing: {
route": {
color: "#ff815b",
width: 3
},
mode: {
type: "fastest",
transport: "truck",
traffic: "traffic:disabled"
}
}
},
appId: YOUR_APP_ID,
appCode: YOUR_APP_CODE
},
computed: {
route() {
return this.property.routing.route
},
routingParameters() {
return {
mode:
this.property.routing && this.property.routing.mode
? Object.values(this.property.routing.mode).join(';')
: ''
}
}
},
async created() {
await this.initMap()
},
beforeDestroy() {
this.map = null
},
methods: {
async initMap() {
this.platform = await new H.service.Platform({
apikey: YOUR_API_KEY
})
await this.getCoordinates()
this.createMap()
},
getCoordinates() {
if (this.property.lat && this.property.lng) {
this.coordinates = { lat: this.property.lat, lng: this.property.lng }
} else {
this.getGeoCoordinates()
}
},
getGeoCoordinates() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(pos => {
this.coordinates = {
lat: pos.coords.latitude,
lng: pos.coords.longitude
}
})
} else {
console.warn('This browser does not support geolocalization.')
}
},
calculateWaypoints() {
if (this.property.routing && this.property.routing.waypoints) {
this.waypoints = this.property.routing.waypoints.map((item, index) => {
this.routingParameters[`waypoint${index}`] = `geo!${item.lat},${
item.lng
}`
})
} else {
this.routingParameters.waypoint0 = this.shipment
? `geo!${this.shipment.from_address.lat},${
this.shipment.from_address.lng
}`
: null
this.routingParameters.waypoint1 = this.shipment
? `geo!${this.shipment.to_address.lat},${
this.shipment.to_address.lng
}`
: null
}
},
calculateRoute() {
this.platform.getRoutingService().calculateRoute(
this.routingParameters,
result => {
if (result.response.route) {
let route = result.response.route[0]
let lineString = new H.geo.LineString()
route.shape.forEach(function(point) {
let parts = point.split(',')
lineString.pushLatLngAlt(parts[0], parts[1])
})
let routeLine = lineString
? new H.map.Polyline(lineString, {
style: {
strokeColor: this.route.color || '#000000',
lineWidth: this.route.width || 2
}
})
: null
this.drawWaypoints(route)
let mapObjects = [...this.markers, routeLine]
this.map.addObjects(mapObjects)
this.map.getViewModel().setLookAtData({
bounds: routeLine.getBoundingBox()
})
}
},
error => {
console.log(error)
}
)
},
drawWaypoints(route) {
route.waypoint.map(({ mappedPosition }, index) => {
this.markers.push(
new H.map.Marker(
{
lat: mappedPosition.latitude,
lng: mappedPosition.longitude
},
{ icon: this.icon }
)
)
})
},
async createMap() {
this.icon = new H.map.Icon(`/${this.property.markerIcon}.svg`)
let defaultLayers = await this.platform.createDefaultLayers()
this.map = new H.Map(
this.$refs[this.ref],
defaultLayers.vector.normal.map,
{
zoom: this.property.zoom,
center: this.coordinates
}
)
let events = new H.mapevents.MapEvents(this.map)
let behavior = new H.mapevents.Behavior(events)
let ui = H.ui.UI.createDefault(this.map, defaultLayers)
this.calculateWaypoints()
this.calculateRoute()
window.addEventListener('resize', () => {
this.map.getViewPort().resize()
})
}
}
}
</script>
<style lang="scss">
.here-map {
&__map {
height: 400px;
margin: 0 auto;
}
}
</style>
Thank you in advance.
Yes, we have a blog how to implement HERE JS API into VueJs but basically we don't realize а technically support an integration of third part libraries/frameworks with HERE JS API.
But any way some recommendations:
Please include all HERE JS libraries (mapsjs-core.js, mapsjs-service.js etc.) into the <head> HTML element like in our examples https://developer.here.com/documentation/examples/maps-js
Please keep the description how to initialize the map in our blog https://developer.here.com/blog/showing-a-here-map-with-the-vue.js-javascript-framework. There is "Because the map is a DOM component, we need to wait until the components have rendered before we try to work with it, so we can’t do it in the created method. Instead we can use the mounted method". But in your code you use created method.
Keep in mind that HERE map container element should not be part of Virtual DOM of Vue
I'm trying to implement the OverlappingMarkerSpiderfier for my Google Maps, and it works because my markers are able to "spiderfy" when I click on a marker.
My issue is that in my dev console on VS Code, ESLint is still giving me the error 'OverlappingMarkerSpiderfier' is not defined. I don't really know what the issue is since my markers are working as intended when I click on them. Below is a picture showing that OverlappingMarkerWorkers even though there is an error from ESLint:
I want to get rid of the error in case a future error arises because of it. I've searched for solutions, and many people have commented that OverlappingMarkerSpiderfier should be loaded after Google Maps load. I've done that, but the error still persists.
I load my Google Maps asynchronously; below is my .js file that loads the Google Maps and OverlappingMarkerSpiderfier:
import api_keys from './api_keys'
const API_KEY = api_keys.google_maps_api_key;
const CALLBACK_NAME = 'gmapsCallback';
let initialized = !!window.google;
let resolveInitPromise;
let rejectInitPromise;
const initPromise = new Promise((resolve, reject) => {
resolveInitPromise = resolve;
rejectInitPromise = reject;
});
export default function init() {
if (initialized) return initPromise;
initialized = true;
window[CALLBACK_NAME] = () => resolveInitPromise(window.google);
const script = document.createElement('script');
script.async = true;
script.defer = true;
script.src = `https://maps.googleapis.com/maps/api/jskey=${API_KEY}&callback=${CALLBACK_NAME}`;
script.onerror = rejectInitPromise;
document.querySelector('head').appendChild(script);
const spiderfier = document.createElement('script');
spiderfier.defer = true;
spiderfier.src = "https://cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier/1.0.3/oms.min.js";
spiderfier.onerror = rejectInitPromise;
document.querySelector('head').appendChild(spiderfier);
return initPromise;
}
The following is my GoogleMaps component. The OverlappingMarkerSpiderfier implementation is located within "watch":
<template>
<div id="google-map">
</div>
</template>
<script>
import gMaps from '../lib/gMaps.js'
export default {
name: 'GoogleMaps',
props: {
events: Array
},
data() {
return {
map: null,
locations: []
}
},
async mounted() {
try {
const google = await gMaps();
const geocoder = new google.maps.Geocoder();
this.map = new google.maps.Map(this.$el);
geocoder.geocode({ address: 'USA'}, (results, status) => {
if (status !== 'OK' || !results[0]) {
throw new Error(status);
}
this.map.setCenter(results[0].geometry.location);
this.map.fitBounds(results[0].geometry.viewport);
});
} catch (error) {
console.error(error);
}
},
watch: {
async events() { //creates markers for the map; data is from a 3rd party API that is handled by a different component
try {
const google = await gMaps();
var oms = new OverlappingMarkerSpiderfier(this.map, {
markersWontMove: true,
markersWontHide: true,
basicFormatEvents: true
})
for(let i = 0; i < this.events.length; i++) {
let marker = new google.maps.Marker({
position: {
lat: parseInt(this.events[i].latitude, 10),
lng: parseInt(this.events[i].longitude, 10)
},
map: this.map,
title: this.events[i].title
})
let iw = new google.maps.InfoWindow({
content: this.events[i].description || 'No description available.'
});
google.maps.event.addListener(marker, 'spider_click', function() {
iw.open(this.map, marker);
});
oms.addMarker(marker);
}
}
catch(error) {
console.error(error)
}
}
}
}
</script>
<style lang="scss" scoped>
#google-map {
width: auto;
height: 100vh;
}
</style>
try either 1 of these
this.$nexttick(()=>{
code in mounted hook....
})
check if window.google object is loaded and your map reference is available before instantiating OverlappingMarkerSpiderfier.
For some reasons, I have to use new google.maps.Marker() with vue2-google-maps, but I don't know how to start since the documents and many people use <GmapMarker ... /> in the HTML part instead.
I've tried to search but the document doesn't cover this.
Right now my code looks like this, it doesn't have any error but it doesn't work either (the map is present but the marker isn't shown):
<template>
<div style="height: 100%; width: 100%;">
<GmapMap
:center="{ lat: 0, lng: 0 }"
ref="mapRef"
>
</GmapMap>
</div>
</template>
<script>
import * as VueGoogleMaps from 'vue2-google-maps';
export default {
computed: {
google: VueGoogleMaps.gmapApi,
},
methods: {
init() {
new this.google.maps.Marker({
position: {
lat: 0,
lng: 0
},
map: this.$refs.mapRef,
});
}
},
async mounted() {
this.init()
},
}
</script>
Ok, I figured out. Here's what I did:
Create a map variable in data()
data() {
return {
map: undefined,
}
},
Set it using this function in mounted()
mounted() {
this.$refs.mapRef.$mapPromise.then((map) => {
this.map = map;
this.init();
});
},
Now, Bob's your uncle, you can use this.map where ever you want
methods: {
init() {
new this.google.maps.Marker({
position: {
lat: 0,
lng: 0
},
map: this.map,
});
},
}
Trying to implement google map into Vue component. But having a hard time. Actually, there is no error. But no map also :) Okay, what I tried so far down below.
In laravel blade I set my api.
<script async defer src="https://maps.googleapis.com/maps/api/js?key={{env('GOOGLE_MAPS_API')}}&callback=initMap"></script>
Then in Vue component;
data() {
return {
mapName: "map",
//some other codes
}
},
mounted() {
this.fetchEstates();
},
methods: {
fetchEstates(page = 1) {
axios.get('/ajax', {
params: {
page
}}).then((response) => {
// console.log(response);
this.estates = response.data.data;
//some other codes....
//some other codes....
},
computed: {
//some other functions in computed...
//
initMap: function(){
var options =
{
zoom : 6,
center : {
lat:34.652500,
lng:135.506302
}
};
var map = new google.maps.Map(document.getElementById(this.mapName), options);
var marker = new google.maps.Marker({
map: map,
icon: 'imgs/marker.png',
url: "/pages/estates.id",
label: {
text: this.estates.price,
color: "#fff",
},
position: {
lat: this.estates.lat,
lng: this.estates.lng
}
});
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
}
<div id="map"></div>
and last marker url id bind is in controller like this,
public function details($id)
{
$estates = allestates::where('id', $id)->first();
return view('pages.details', compact('estates'));
}
Do I missing something in Vue js? Thank you!
From our discussion in the comments, I realise that your issue is because this.estates is still not defined when initMap() is executed. Remember that you are using an asynchronous operation (via axios) to populate this.estates, so it is undefined at runtime. What you can do is:
Keep the map initialisation logic in initMap()
Move all the Google Map marker creation until after the axios promise has been resolved. You can abstract all that into another method, e.g. insertMarkers()
Also, remember that you need to define estates in the app/component data, otherwise it will not be reactive.
Here is an example:
data() {
return {
mapName: "map",
// Create the estate object first, otherwise it will not be reactive
estates: {}
}
},
mounted() {
this.fetchEstates();
this.initMap();
},
methods: {
fetchEstates: function(page = 1) {
axios.get('/ajax', {
params: {
page
}}).then((response) => {
this.estates = response.data.data;
// Once estates have been populated, we can insert markers
this.insertMarkers();
//pagination and stuff...
});
},
// Iniitialize map without creating markers
initMap: function(){
var mapOptions =
{
zoom : 6,
center : {
lat:34.652500,
lng:135.506302
}
};
var map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
},
// Helper method to insert markers
insertMarkers: function() {
var marker = new google.maps.Marker({
map: map,
icon: 'imgs/marker.png',
url: "/pages/estates.id",
label: {
text: this.estates.price,
color: "#fff",
},
position: {
lat: this.estates.lat,
lng: this.estates.lng
}
});
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
}
},
Update: It also turns out that you have not addressed the issue of the data structure of this.estates. It appears that you are receiving an array from your endpoint instead of objects, so this.estates will return an array, and of course this.estates.lat will be undefined.
If you want to iterate through the entire array, you will have to use this.estates.forEach() to go through each individual estates while adding the marker, i.e.:
data() {
return {
mapName: "map",
// Create the estate object first, otherwise it will not be reactive
estates: {}
}
},
mounted() {
this.fetchEstates();
this.initMap();
},
methods: {
fetchEstates: function(page = 1) {
axios.get('/ajax', {
params: {
page
}}).then((response) => {
this.estates = response.data.data;
// Once estates have been populated, we can insert markers
this.insertMarkers();
//pagination and stuff...
});
},
// Iniitialize map without creating markers
initMap: function(){
var mapOptions =
{
zoom : 6,
center : {
lat:34.652500,
lng:135.506302
}
};
var map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
},
// Helper method to insert markers
insertMarkers: function() {
// Iterate through each individual estate
// Each estate will create a new marker
this.estates.forEach(estate => {
var marker = new google.maps.Marker({
map: map,
icon: 'imgs/marker.png',
url: "/pages/estates.id",
label: {
text: estate.price,
color: "#fff",
},
position: {
lat: estate.lat,
lng: estate.lng
}
});
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
});
}
},
From what I can see in the screenshot you posted, this.estates is an array of objects? If that's the case you need to iterate through the array using forEach
this.estates.forEach((estate, index) => {
console.log(estate.lat);
//handle each estate object here
});
or use the first item in the array like so this.estates[0].lat, if you're only interested in the first item.
I have the following definition for the Vue element:
new Vue({
el: "#app",
data: {
latitude1: 'a',
name: 'aa'
},
mounted() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.latitude1 = position.coords.latitude;
})
} else {
this.latitude1 = "WTF??"
// this doesn't work either:
// this.$nextTick(() => { this.latitude1 = "WTF??" })
}
},
methods: {
// button works... WTF?!?
doIt() {
this.latitude1 = "WTF??"
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<div>{{ latitude1 }}: {{ name }}</div>
<button #click="doIt">Do it</button>
</div>
I can see the location data being populated. The alert displays the latitude but the 2 way binding for the data field latitude1 is not working.
I have tried storing the object state using this and that also did not work.
My html is as follows:
<div class="form-group" id="app">
<p>
{{latitude1}}
</p>
</div>
One of the things to do inside the Vue.js is to use the defined methods for reactive properties changes.
Here is a code I've provided for it:
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
new Vue({
el: "#app",
data: {
latitude1: 'a',
name: 'aa'
},
mounted: function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
console.log(position.coords.latitude);
Vue.set(this, 'latitude1', position.coords.latitude);
}, error, options)
}
}
});
I also set error handler and options for the navigator query. For following the results please check the console.