Hi, I have created a field for geolocation. I want to retrieve the latitude and longitude data from Java, but it is always empty. Where is my mistake?
import { html, css, LitElement } from 'lit';
class GeoLocationElement extends LitElement {
static styles = css`
:host {
display: block;
}
`;
static properties = {
latitude: { type: Number },
longitude: { type: Number },
locationAvailable: { type: Boolean },
};
constructor() {
super();
this.locationAvailable = false;
this.latitude = null;
this.longitude = null;
}
connectedCallback() {
super.connectedCallback();
this.checkGeoLocationPermission();
}
checkGeoLocationPermission() {
navigator.permissions.query({ name: 'geolocation' }).then((result) => {
if (result.state === 'granted') {
this.getLocation();
} else if (result.state === 'prompt') {
this.showMessage();
} else if (result.state === 'denied') {
this.showMessage();
}
});
}
getLocation() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.locationAvailable = true;
this.dispatchEvent(new CustomEvent('location-updated'));
},
(error) => {
console.error('Geolocation error:', error);
this.dispatchEvent(new CustomEvent('location-error', { detail: error }));
}
);
}
showMessage() {
alert('You have not enabled geolocation');
}
render() {
return html`
<p>Latitude: ${this.latitude !== null ? this.latitude.toFixed(6) : ''}</p>
<input type="hidden" part="latitude" value="${this.latitude !== null ? this.latitude.toFixed(6) : ''}" />
<input type="hidden" part="longitude" value="${this.longitude !== null ? this.longitude.toFixed(6) : ''}" />
<p>Longitude: ${this.longitude !== null ? this.longitude.toFixed(6) : ''}</p>
`;
}
}
window.customElements.define('geo-location-element', GeoLocationElement);
package com.company.hotelmonitoring.component;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Synchronize;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.dependency.JsModule;
import io.jmix.flowui.data.SupportsValueSource;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
@Tag("geo-location-element")
@JsModule("geo-location-element/geo-location-element.js")
public class GeoLocationElement extends Component implements ApplicationContextAware {
protected ApplicationContext applicationContext;
public GeoLocationElement(){
}
@Synchronize(property = "latitude", value = "latitude")
public String getLatitude(){ return getElement().getProperty("latitude");}
@Synchronize(property = "longitude", value = "latitude")
public String getLongitude(){ return getElement().getProperty("longitude");}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
Kind regards
Swara