In my current project, I am utilizing an Oracle 12c database, APEX 5, and the Google Maps API.
What I am trying to achieve is plotting the coordinates of each sighting from the sighting
table onto the map. To accomplish this, I prepare the map before entering the loop to ensure that the same map is used for all markers. The necessary javascript functions are called within a dynamic page load action.
DECLARE
l_lng NUMBER;
l_lat NUMBER;
l_id NUMBER(5,0);
htp.print('<html>');
htp.print('<head>');
htp.print('<style>
#map {
width: 500px;
height: 400px;
}
</style>
');
htp.print('
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initializeMap() {
var myLatLng = {
lng: -4.083020,
lat: 50.315239
};
map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: myLatLng
});
}
</script>
');
BEGIN
FOR sighting_rec IN
(SELECT id, species_id FROM sighting ORDER BY id
)
LOOP
SELECT sighting.id,
t.x Longitude,
t.y Latitude
INTO l_id,
l_lng,
l_lat
FROM sighting,
TABLE(sdo_util.getvertices(sighting.location)) t
WHERE sighting.id = sighting_rec.id;
htp.print('
<script>
function initializeMarkers() {
var myLatLng = {
lng: ' || l_lng || ',
lat: ' || l_lat || '
};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: ' || l_id || '
});
}
</script>
');
htp.print('</head>');
END LOOP;
htp.print('
<body>
<div id="map"></div>
</body>
');
htp.print('</html>');
END;
Despite fetching all the records successfully, only one marker is being displayed on the map. This can be confirmed by adding
DBMS_OUTPUT.PUT_LINE(l_lat || ',' || l_lng);
after WHERE sighting.id = sighting_rec.id;
which prints all the retrieved coordinates.
-4.083592,50.31548
-4.083639,50.315456
-4.083714,50.315475
The issue seems to be that the marker is being recreated with each iteration of the loop. I attempted to use
var ' || l_id || ' = new google.maps.Marker
but this action prevented the map from loading altogether. Any suggestions on how to resolve this would be appreciated!
This is how the HTML output appears in the browser:
<script>
function initializeMarkers() {
var myLatLng = {
lng: -4.083592,
lat: 50.31548
};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 12
});
}
</script>
<script>
function initializeMarkers() {
var myLatLng = {
lng: -4.083639,
lat: 50.315456
};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 13
});
}
</script>
<script>
function initializeMarkers() {
var myLatLng = {
lng: -4.083714,
lat: 50.315475
};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 14
});
}
</script>