Is there a way to continuously iterate this PL/SQL statement in order to display numerous markers on my Google map?

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>

Answer №1

You are facing an issue with having multiple initializeMarkers functions, and only one will be executed based on the browser. It is recommended to consolidate all marker initialization into a single function and ensure that it is being called properly (I couldn't locate where intializeMap or initializeMarkers functions are being invoked, but if you are seeing a map with markers, then they must be called somewhere in the code).

htp.print('<script>
    function initializeMarkers() {');

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(' 
            var myLatLng = {
                lng: ' || l_lng || ',
                lat: ' || l_lat || '
            };

            var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: ' || l_id || '
            });');

  END LOOP;

htp.print('}
    </script>
');
htp.print('</head>');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2: Harnessing the power of Observables with multiple Events or Event Handlers

In the component template, I have grouped multiple Inputs and their events like this: <tr (input)="onSearchObjectChange($event)"> <th><input [(ngModel)]="searchObject.prop1"></th> <th><input [(ngModel)]="searchObje ...

Avoid accidental overwrites in localStorage using JavaScript

I've been working on a Vue project where I'm implementing a shopping cart feature. In this setup, when the user clicks on a button, the item details are stored in localStorage and then displayed in the shopping cart interface. However, I encount ...

Is there a way I can create a conditional statement to determine the values of my selection?

I need to customize the order status values for 'confirmed', 'on the way' and 'delivered'. How can I map these statuses to specific numerical values based on the options available in a select menu? Confirmed - 10 On the way - ...

The browser is not showing JavaScript alerts and prompts when they are called inside a function

/*I am attempting to run a color guessing game in my browser, but when I try opening the code in Chrome, it doesn't work. Any suggestions or ideas would be greatly appreciated.*/ var colors = ["Aqua", "Black", "Blue", "Brown", "Coral", " ...

The relationship between two distinct servers: Express.js and Node.js

Working with the Express.js framework and Node.js, I am trying to make a request to an MS SQL database on the server side. My goal is to retrieve data (in JSON or array format) from the server and send it to the client side. I'm unsure about how to ...

What are some ways to enhance the functionality of the initComplete feature in Dat

$('#example').dataTable( { "initComplete": function(settings, json) { alert( 'DataTables has finished its initialisation.' ); } } ); Is there a way to extend the initComplete function for other languages? $.extend( true, $.f ...

Reveal and conceal information with a customized web address

I have a PHP and MySQL blog that I want to display in a div using show and hide JavaScript functions. Everything works fine with other divs, but the issue arises when clicking on a vanity URL causing my webpage to refresh every time it's clicked. The ...

Ensure that this regular expression is able to accurately match all numbers, even those without decimal points

Seeking help to create a script that can extract the negative percentage value between two numbers. One of the numbers is dynamic and includes different currencies, decimals, etc., so I believe a regex is needed for this task. The current script works, but ...

What causes a stack trace to be logged alongside a rejected Promise in Node version 7.2.0?

After executing this code in Node 7.2.0: let prms = Promise.reject(new Error('error')); prms.catch(() => {}); console.log(prms); I anticipated Promise {<rejected> Error: error} to be displayed on the console, however I was instead pre ...

An error arises when using the command window.close()

I have encountered an issue with this code where it closes all Safari windows but works fine in Internet Explorer. What should I do? Is there an alternative method for closing the current opened window in every browser? <input type='button' v ...

Passing default props to a component in React that includes a function as one of the

I am working on a React component that has default props set. The issue arises when I try to pass an additional prop, specifically a function. class MyComponent extends Component { constructor(props) { console.log('props', props); supe ...

The Facebook Customer Chat Plugin embedded within an iframe

Can the Customer Chat Plugin be used within an iframe? When adding content-security-policy: frame-ancestors IFRAME_DOMAIN, it displays the message Refused to frame 'https://www.facebook.com/' because an ancestor violates the following Content Se ...

Using JavaScript to extract variables from parsed JSON data

Could someone please help me understand how to run this code smoothly without encountering any errors? var test = 'Something'; JSON.parse('{"xxx": test}'); I am inquiring about this because I have a JSON object containing variables th ...

ReactJS library encounters "Failed to load PDF file." error intermittently while attempting to view a PDF file

I recently developed a React JS application using create-react-app and decided to incorporate react-pdf for viewing PDF files. However, I've encountered an intermittent issue where the PDF sometimes fails to load. Specifically, when I initially load t ...

Send the image URL to the JavaScript function

Is there a way to resolve the error I'm encountering when attempting to pass my uploaded photo to JavaScript on a page? werkzeug.routing.BuildError BuildError: ('uploaded_file', {'filename': u'user/user-1/scan.jpeg'}, N ...

Is it possible to utilize jQuery's .wrap or .wrapInner to encase a variety of elements within them?

I am working with a HTML structure that looks like this: <section> <item> <ele class="blue" /> <ele class="green" /> <ele class="red" /> </item> <item> <ele class="blue" /> <ele ...

Utilizing the Google Translate API within an ASP MVC framework to translate a div's content from English to Arabic

Currently, I am working on a small project that involves two divs: one for English and another for Arabic. Despite creating the project, I am encountering an issue with getting the translation from English to Arabic. Below is the code I have attempted, but ...

The Angular http.post function seems to be returning null responses consistently, without any actual data being received

When making a post call in Angular using Http.post, I am sending jsonData as a parameter with the following formatted data. However, every time I receive a response as null. Could you please review my code and let me know if there are any mistakes? Here ...

Generating a JSON object through the comparison of two other JSON objects

I need to create a new JSON object called selectedProductAttributes, which is generated by comparing the contents of a second JSON object (selectedProductAttributesNames) with a third object (allProductAttributes). Let me provide some examples to make this ...

Incorporating Subtitles into Videos using NodeJS and the FFMpeg Fluent API

I'm having trouble adding subtitles (srt) to a video stream using Node JS and FFMpeg... Here's what I've tried: var command = ffmpeg(file.createReadStream()) .input("C:\\code.srt").videoCodec('copy') .videoCodec(& ...