What is the process for incorporating markers from a JSON file into a PHP webpage using AJAX?

My goal is to display markers on a PHP page using the Google Maps API controlled by radio buttons. All marker data is loading correctly (via JSON), but the map itself is not rendering. I have checked for script exceptions in the console and the run() method successfully retrieves all latitude, longitude, and value data!

        <script>
            var latlng = { lat: 19.7999, lng: 42.5121 };
            var marker;
            var map;
            var markers=[];

            function addmarker(map, lat, lng, title ){
                  marker = new google.maps.Marker({
                  position:{ lat:lat,lng:lng },
                  title:title,
                  draggable:true,
                  map:map
                });
                markers.push( marker );
            }
            function initialize() {
                var mapCanvas = document.getElementById('mapArea');
                var mapOptions = {
                  center: latlng,
                  zoom: 19,
                  mapTypeId: google.maps.MapTypeId.SATELLITE
                }
            }
            google.maps.event.addDomListener(window, 'load', initialize);
            </script>
            <script>
                function run() {
                    var radio = "";
                    for (i = 0; i < document.getElementsByName('rd').length; i++) {
                        if (document.getElementsByName('rd')[i].checked) {
                            radio = document.getElementsByName('rd')[i].value;        
                        }        
                    }
                    initialize();
                    $.ajax({
                      dataType: 'JSON',
                      url: 'http://ws.net/data.php?' + radio,
                      success: function(data) {
                          markers.forEach( function( e,i,a ){
                             e.setMap( null ); 
                          });

                          for( var o in data ){
                            var lat=Number(data[o].lat);
                            var lng=Number(data[o].lon);
                            var val= data[o].value;                             
                            
                            addmarker.call( this, map, lat, lng, val );
                          }
                      },
                      error: function( err ){
                        console.log( err );  
                      }
                    })
                }                    
            
        </script>    

    <body  >       
       <form action="" method="post">
            <input type="radio" value="car" name="rd"  />Car.
            <input type="radio" value="bike" name="rd" />Bike
            <input type="button" value="send"  onclick="run();"/>
       </form>  
       <div id="mapArea" style="width: 1000px; height: 600px;"> </div>
    </body>
</html>

Answer №1

  • To set up the map initially, insert this line of code inside the initialize() function:
  map = new google.maps.Map(mapCanvas, mapOptions);

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

Go to a specific component located in a different module within Angular

I have a default app.component that contains a button. When this button is clicked, I want to navigate to the login.component. Below is a snippet from my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; ...

update confirmed data from a record

I am facing a unique challenge, where I have an edit form that updates a record in a table. One of the fields, let's say username, needs to be unique. To validate this, I am using the jQuery validation plugin along with the remote method as shown belo ...

Is there a way to recognize AJAX requests within Python's Flask framework?

Is there a way to identify if the browser sent an AJAX request through AngularJS, allowing me to respond with a JSON array? Alternatively, if not an AJAX request, I need to know how to render the template. Any suggestions? ...

Sharing information between controllers from diverse modules

We are currently in the process of developing a Telecom App dashboard. Our goal is to retrieve logs using Logstash and Elastic search, and then present them on the UI using the ng-Table directive of Angularjs. While we have successfully obtained the logs, ...

Issue with resizing browser window when using three.js EffectComposer

My current rendering setup encounters a resizing issue when adjusting the browser window size. In my setup, I am rendering two scenes - one for objects with postprocessing effects applied. The postprocessing effects are achieved using THREE.EffectComposer ...

Conceal the <p> tag if the content inside is either "0" or blank

I'm currently working on a basic calculator project and I've hit a roadblock. I need to hide certain elements based on conditions. The code snippet with explanations is provided below. function calculateArea() { var length = document.getElem ...

jQuery failing to append code after being removed

I need some assistance with an issue I've run into while using jQuery's .remove(). Here is a snippet of code that showcases the problem: $( '.video-button span.glyphicon-play' ).click(function() { $( '#video-player' ).ap ...

"Vibrant hues in a flask with interactive colorbox

I am currently using Jquery colorbox in conjunction with Flask. Upon the user clicking on an icon, a URL is submitted by the script to display a form within the colorbox. Once the user clicks the save button, the form is submitted and the colorbox is close ...

Configuring Spring properties by using @PropertySource along with an external JSON file

Currently, I am utilizing Spring Boot in conjunction with Keycloak access. In this setup, I have stored the Keycloak configuration details within a keycloak.json file and aim to extract these values using the PropertySource annotation... Here's an ex ...

Is there a way to modify page URLs without causing a refresh, regardless of browser?

Despite my extensive searches on various online platforms, including stackoverflow, I have yet to come across a satisfactory answer to my question. While I find the window.history.pushState() and window.history.replaceState() methods quite user-friendly, ...

Javascript Countdown Timer for HTML5 Canvas Animation

I'm currently working on a countdown in javascript using createJS for Flash Canvas HTML5, however, I've encountered the following error: file_Canvas.js:318 Uncaught TypeError: Cannot read property 'dtxt_days' of undefined This error sp ...

What is the best way to access a Python API or local data within the Google Visualization DataTable JavaScript library?

I have been tirelessly working for the past two weeks to figure out how to load a local CSV file into google.visualization.DataTable() or use Ajax to call a Python Flask API that I created. My ultimate goal is to dynamically create a Gantt chart. Here&apo ...

What is the best way to include a JavaScript variable within CSS styling?

I am currently implementing a dropdown menu system where the image of a parent div changes on mouse hover over a link, and reverts back when the mouse moves away. I have this functionality set up using a variable in my HTML code. Is there a way for me to m ...

Ajax is not able to trigger a POST request to a PHP form

My form is not posting for some unknown reason, despite everything else on my server functioning properly. Below is the code snippet in question: PHP <?php if(isset($_POST['field1']) && isset($_POST['field2'])) { $data ...

I'm seeking assistance with troubleshooting an error related to the post request in my python API. Any help would be greatly appreciated

I recently developed code to display information about specific cars. Initially, I compiled a list detailing various types of cars such as their make, model, year, etc. The code successfully retrieves all data or a particular type of data utilizing a URL. ...

Masking text in React Fiber/Drei can be achieved through a variety

Can you use a <Text>/<Text3D> to mask another object, like shown in this image where text is masking a cube? I have looked at examples on pmndrs/drei and tried various methods with replacing other objects, but I am unable to achieve the desire ...

Unable to access the variable field of MongoDB in JavaScript

I'm facing an issue while trying to loop through an array I retrieved from mongodb. It seems the array is treated as a single element, and here is the code snippet: const project = await Project.findOne({ embedId: inititalData.embedId }); console. ...

Serialize Jackson without including any properties

My JSON structure currently looks like this: { "name": "LS", "stocks": [ { "x": 1500234365000, "y": 0.000000000000 }, { "x": 1500234427000, "y": 0.000015154000 }, { "x": 1500234 ...

The connection between Android and the MYSQL database has returned a null value

I have been encountering an issue while trying to fetch specific data from my MySQL database using Android to pass parameter values and then reading this value in a PHP script within the query to retrieve the data. Every time I run the application, I face ...

Perform a series of observables from a dynamically generated array

Currently, I am in the midst of a project (Angular2) where I am dynamically creating Observables and storing them in an array. var ObservableArray : Observable<any>[] = []; //populating the Observable array dynamically for (var i = 0; i < this.ma ...