I am trying to use the new Google map API to show a map then add markers to it when a server sent event is fired that sends GPS coordinates.
My google map code that shows a map is as following:
var coordinates = [["19:55",123.57,-456.64,"08/03/2024","UTC+0",126]];
var map = {};
var latlngbounds = {};
async function initMap() {
// Request needed libraries.
const {Map} = await google.maps.importLibrary('maps');
const { AdvancedMarkerElement } = await google.maps.importLibrary('marker');
map = new Map(document.getElementById('map'), {
center: { lat: coordinates[0][1], lng: coordinates[0][2] },
zoom: 14,
gestureHandling: 'greedy',
mapId: 'XXXXXXX',
});
latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < coordinates.length; i++) {
latlngbounds.extend({ lat: coordinates[i][1], lng: coordinates[i][2] });
const marker = new AdvancedMarkerElement({
map,
position: { lat: coordinates[i][1], lng: coordinates[i][2] },
});
}
map.fitBounds(latlngbounds);
}
initMap();
I made map and latlngbounds global variables to be easy to manipulate them.
My server sent event code in JavaScript that is supposed to add a marker to the map when new coordinates are sent by the server is as following:
window.onload = function(){
var source = new EventSource("sse");
//On SSE data reception.
source.onmessage = function (event) {
var parsedJson = JSON.parse(event.data);
//If data received is different than the data already used.
coordinates = parsedJson;
latlngbounds.extend({ lat: lastCoordinates[0][1], lng: lastCoordinates[0][2] });
const marker = new AdvancedMarkerElement({
map,
position: { lat: lastCoordinates[0][3], lng: lastCoordinates[0][4] },
});
map.fitBounds(latlngbounds);
};
};
I’m getting as error Uncaught InvalidValueError
I changed the code as below but I still get an error Uncaught (in promise) InvalidValueError
Is what I’m trying to do impossible with this new Google map API?
window.onload = function(){
var source = new EventSource("sse");
//On SSE data reception.
source.onmessage = async function (event) {
var parsedJson = JSON.parse(event.data);
//If data received is different than the data already used.
coordinates = parsedJson;
latlngbounds.extend({ lat: lastCoordinates[0][1], lng: lastCoordinates[0][2] });
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
const marker = new AdvancedMarkerElement({
map,
position: { lat: lastCoordinates[0][3], lng: lastCoordinates[0][4] },
});
map.fitBounds(latlngbounds);
};
};