How to drop several pins on Google Maps with JavaScript

I am working on incorporating multiple markers into a Google map using ajax, javascript, and php. Although there are no errors in my code, the markers are not appearing as expected. I would greatly appreciate any assistance with this issue. Please refer to the sample output of AJAX DATA below:

Array(3409)
[0 … 99]
0 : {GPS_COORDINATES: "14.901177,120.867704"}
1 : {GPS_COORDINATES: "14.620365,120.577517"}
2 : {GPS_COORDINATES: "14.869043,120.463918"}
...

Click here for a screenshot of AJAX DATA

Below is the AJAX code I have implemented:

function initMap() {

  var map;

  $.ajax({
    url: "retailer-marker.php",
    method: "POST",
    data: {
      search: search,
      coordinator: coordinator
    },
    dataType: "json",
    success: function(data) {

      
      // Add your implementation logic here

   
    },
    error: function(data) {
      console.log("error");
    }
  });
}

And here is the PHP CODE snippet:

    $sql = "SELECT GPS_COORDINATES FROM ret_retailer";

$result = mysqli_query($conn, $sql);

$data = array();
foreach ($result as $row) {
    $data[] = $row;
} 

print json_encode($data);

Answer №1

Your data array consists of objects, meaning that using data[i][0] will not work. You should instead use data[i].GPS_COORDINATES.

In conclusion, the following code should function correctly:

var position = new google.maps.LatLng(data[i].GPS_COORDINATES);

If you had simply executed a console.log(data[i]), this issue would have been apparent.

Edit:

The problem lies in how you are creating the LatLng object. The LatLng method requires 2 arguments (latitude and longitude), but you are only passing one (a string containing both values). Here is a solution:

for (var i = 0; i < data.length; i++) {

  var coords = data[i].GPS_COORDINATES.split(','); // Split the string to obtain separate latitude and longitude values
  var position = new google.maps.LatLng(coords[0], coords[1]); // Utilize these values as required by LatLng method

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

Additionally, ensure you declare your variables properly using the var keyword, such as var i = 0; and var marker = ....

Answer №2

<!DOCTYPE html>
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
<title>Displaying Multiple Markers on Google Maps</title> 
 <script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script>
</head> 
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  center: new google.maps.LatLng(-33.92, 151.25),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, index;

for (index = 0; index < locations.length; index++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[index][1], locations[index][2]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, index) {
    return function() {
      infowindow.setContent(locations[index][0]);
      infowindow.open(map, marker);
    }
  })(marker, index));
}
</script>
</body>
</html>

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

Exploring the variances in cURL header options

Can you explain the difference between the two sets of headers sent by cURL? $header="POST /cgi-bin/webscr HTTP/1.1\r\n"; $header .="Content-Type: application/x-www-form-urlencoded\r\n"; $header .="Host: www.paypal.com\r\n"; ...

Enhance the URL with a search form for including the 'sku'

Currently, I have a search form on my website that successfully refreshes the page when the submit button is pressed, displaying the table of results below. The URL generated by this form is http://example.com/?txtKeyword=searchterm. However, I am looking ...

Utilizing Vue.js and i18n to fetch external JSON files from a server and seamlessly integrating them as globally accessible data in all components

I'm currently exploring ways to fetch translation files from a server and make them accessible across all components of the project. For instance, I can request to obtain this JSON: { "DASHBOARD_SETTINGS": "Einstellungen", ...

Create a PDF document with pdfkit and stream it to the browser in a Node.js Express application

I am currently using pdfkit to create a PDF file and I would like to send this PDF directly to the browser. However, I am encountering an error message stating "TypeError: listener must be a function", Additionally, the file is being generated in m ...

Restore Bootstrap Dropdown values to their initial settings when clicked

I need a button that can reset all filter dropdown values to their default values. The current code I have only changes all values to "Filter" when reset, but I specifically need it to reset to "Car brand" and "Model". Here's my code: // set.... $(" ...

JavaScript: The variable `scopes` is declared

I'm completely new to JavaScript. Can anyone help me understand why this code isn't working, and what changes I need to make to fix it? function getResults(keywords) { foo.foo = function() { var bar = foo.getSomeText; // ...

web application tasks being executed asynchronously

In the web application I'm developing, there are tasks that are too time-consuming to be completed during the http request/response cycle. When a user makes a request, the server needs to run scripts to generate data, like rendering images with povray ...

The global variable is inaccessible when invoked within a dynamically generated function

The variable selected is a global one and accessed using this.selected, which reliably returns the correct value. However, when called from a dynamically created function, it returns unknown. onClick: function(val){ for (i = 0; i < positi ...

Display a notification using C# code

In this WebMethod, the value from the front-end is taken in the "lvl" string. This string is then checked using the "getDuplicate" procedure to see if the value already exists in the database. If the value does exist, the "InsertObject" procedure is not ac ...

nginx's 413 error code is triggered when attempting to upload a file larger than 1Mb

Whenever I attempt to upload a file larger than 1 mb, I encounter an Nginx error. To address this issue, I have adjusted the client_max_body_size to 500M in nginx.conf and also updated post_max_size and upload_max_filesize to 500M in php.ini. ...

Laravel Form Input: Optional Fields

Creating a basic contact form has been my latest project. I want to give users the option to input an order id if they have one, otherwise default it to "0" (considering it as a regular inquiry). This is the code I've implemented: Controller <?ph ...

When using a callback function to update the state in React, the child component is not refreshing with the most recent properties

Lately, I've come across a peculiar issue involving the React state setter and component re-rendering. In my parent component, I have an object whose value I update using an input field. I then pass this updated state to a child component to display t ...

Is there a way to retrieve the Marker that is being dragged when the event handler has already been bound?

How can I identify the Marker that is being dragged when the handler is a bound function? Take a look at this snippet from my react component: constructor() { this.handleMarkerMove = this.handleMarkerMove.bind(this); } createMarker() { const marker ...

What is the comparable javascript code for the <script src="something1.json"></script> tag?

Within my HTML code, I currently have the following line to read a JSON file: <script src="something1.json"></script> Inside this JSON file, there is a structure like so: var varName = { .... } This method of definition naturally sets up ...

Can you provide guidance on converting a text file into JSON format using PHP?

I am facing a challenge with transforming data from a text file into valid JSON format. The data in the file is structured in 8-line sections and my goal is to convert it into a JSON array. data1 data1 data1 data1 data1 data1 data1 data1 data2 data2 data2 ...

Changing values in object using Mongoose in MongoDB

Currently, I have a basic collection stored in MongoDB using Mongoose. My users model consists of a single field of type object, and I am looking to dynamically modify this object. However, despite my attempts using findByIdAndUpdate(), findById, findOne( ...

Troubles with uploading files in Codeigniter

Here is the HTML snippet for a form and file upload: <form action ="<?php echo base_url(); ?>home/register_doctor" method ="POST" enctype="multipart/form-data" accept-charset="utf-8"> ... <input id="file-0" class="file" type="file" multiple ...

Using JavaScript, transform a client's date/time string into a JSON-compatible date/time string

I need to find a way to convert a client's date/time string on a form into a JSON date/time string using JavaScript with moment.js for a Django REST API backend service. Here is the initial attempt: document.getElementById("dt_tm").value = moment(do ...

Encountering an issue with React where the useContext hook is returning undefined instead of

I am facing an issue where I am attempting to access state and setState from the Store file, but it returns as undefined. Can someone help me understand what is causing this problem and how I can resolve it? import React, {createContext, useState} from &ap ...

establishing a header for a curl request on an external domain

I'm currently working on updating some fields on a remote site using curl. So far, I have successfully logged into the remote site and fetched the csrf token required for the curl request. However, I am facing difficulties in setting the header parame ...