So, I was just trying to get current location by using navigator.getlocation.getCurrentLocation
method in Lightning Web Components. When I check if(navigator.getlocation)
, this returns true
.
But when use the method, it always gives me an error like
"afterRender threw an error in 'c:sampleMapComponent' [Cannot read property 'length' of undefined]".
Below is my code of JS file.
/* eslint-disable no-console */
import { LightningElement, track } from 'lwc';
export default class SampleMapComponent extends LightningElement {
@track mapMarkers;
get findMe() {
navigator.geolocation.getCurrentPosition(this.success, this.error);
return this.mapMarkers;
}
success(position) {
if (position) {
console.log('position -> ' + position);
this.mapMarkers = [
{
location: {
'Latitude': position.coords.latitude,
'Longitude': position.coords.longitude
},
title: "My Location",
},
]
}
}
error() {
console.log('Failed');
}
}
Template:
<template>
<h1>Current Location</h1>
<template if:true={mapMarkers}>
<lightning-map map-markers={mapMarkers}></lightning-map>
</template>
Error:
Please let me know what am I doing wrong..I am calling findMe()
method from template (from map-markers of lightning-map)
if
condition that you have mentioned andlength
being used anywhere in the code.