Creating multiple Google markers based on addresses retrieved from a database using PHP

I have a requirement to display multiple Google markers on a map based on addresses stored in a database. I have already successfully loaded an XML file to retrieve latitude and longitude coordinates, but now I need assistance on how to create multiple markers based on address information using PHP or JSON. The code snippet below shows how I loaded the XML file:

<div class="map">
      <div id="map"></div>
    <script>
            var customLabel = {
        restaurant: {
          label: 'R'
        },
        bar: {
          label: 'B'
        }
      };

    // var locs = [ ["-33.863276, 151.207977"],customLabel


        function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(12.92279500, 77.61440500),
          zoom: 12
        });
        var infoWindow = new google.maps.InfoWindow;

          downloadUrl('http://www.rentozy.in/rentozy.xml', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('marker');
            Array.prototype.forEach.call(markers, function(markerElem) {
              var id = markerElem.getAttribute('pg_id');
              var name = markerElem.getAttribute('name');
              var address = markerElem.getAttribute('pg_address');
              var type = markerElem.getAttribute('pg_type');
              var point = new google.maps.LatLng(
              parseFloat(markerElem.getAttribute('lat')),
              parseFloat(markerElem.getAttribute('lng')));

              var infowincontent = document.createElement('div');
              var strong = document.createElement('strong');
              strong.textContent = name
              infowincontent.appendChild(strong);
              infowincontent.appendChild(document.createElement('br'));

              var text = document.createElement('text');
              text.textContent = address
              infowincontent.appendChild(text);
              var icon = customLabel[type] || {};
              var marker = new google.maps.Marker({
                map: map,
                position: point,
                label: icon.label
              });
              marker.addListener('click', function() {
                infoWindow.setContent(infowincontent);
                infoWindow.open(map, marker);
              });
            });
          });
        }
      function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
          }
        };

        request.open('GET', url, true);
        request.send(null);
      }

      function doNothing() {}
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
    </div>

Answer №1

To pinpoint an address on the map, it is recommended to utilize the geocoding service for converting the address into latitude and longitude coordinates. However, it's essential to be mindful of the query limit associated with this service, as depicted in the attached screenshot, as it can easily be surpassed.

<!--
    /*
        https://developers.google.com/maps/documentation/javascript/geocoding
        https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
    */
-->
<!doctype html>

... (omitted for brevity) ...

https://i.stack.imgur.com/fQQLO.jpg

Answer №2

Your feedback is appreciated, however, I prefer not to load an XML file. Instead, I would like to directly input the address into the Google Maps API. All addresses are retrieved from our database and should be sent directly to the Google Maps API.

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

Converting a JavaScript function to CoffeeScript, accepting jQuery's .map function and Selectors as parameters

I'm in the process of converting some JavaScript code into CoffeeScript and encountering an issue with a particular function. Here is the original functioning JS: $(".comformt_QA").change(function(){ var array = $(".comformt_QA").map(function() { ...

Exploring the Functionality of Anchors in Regular Expressions

The symbol "^" indicates that the match must start at the beginning of a line or string. Can you explain what is meant by the term "string" in this context? If we use the expression /^(apple)/, will it match the phrase this applesauce is delicious, since ...

Decoding JSON data from a URL on the Arduino IDE using ESP8266

My process involves programming the esp8266 using the Arduino IDE and connecting to a local network via WIFI. The goal is to download JSON content generated on the local server, with the following code being used: #include <ESP8266WiFi.h> #incl ...

Adding multiple images to email HTML with Python made easy

Looking for a solution to embed 15 .jpg images from a single folder into the body of an email without them shrinking when stacked vertically. My initial approach was to create one long image with all photos but it reduced in size as more pictures were adde ...

Node.js script encounters errors fetching static files

My HTML index.html file has multiple containers, and I have included the bootstrap and font awesome folders in the <head> section like this: <link href="../bootstrap/css/bootstrap.css" rel="stylesheet"> <link href="../bootstrap/css/bootstra ...

Having issues with the onclick() function not functioning properly with Jquery?

Yesterday, I successfully integrated some Jquery code into my website. However, when I attempted to add more code today for a new feature, everything seemed to stop working. Even the code that was functioning perfectly yesterday has now ceased to work. The ...

Is it possible to load JavaScript code once the entire page has finished loading?

My webpage includes a script loading an external JavaScript file and initiating an Ajax query. However, the browser seems to be waiting for example.com during the initial page load, indicating that this external dependency may be causing a delay. Is there ...

Controlling the back DIV while maintaining overlapping layers

I successfully positioned my right hand content on top of the leaflet map in the background using CSS properties like position and z-index. However, I am looking for a way to make the overlapping div not only transparent but also non-interactive while stil ...

Trouble with recognizing nested functions when calling them in an onClick event

Encountering a `not defined` error on the console when attempting to call nested functions with an `onClick` event in an HTML page. After searching for solutions without success, I suspect it may be a scope or closure issue, but I am unsure of how to addre ...

DataTables.js, the powerful JavaScript library for creating interactive tables, and its compatible counterpart

I'm currently making some changes to a dynamic table that require enabling a vertical scroll bar. As a result, I need to implement this vertical scroll bar mechanism on an existing table. The code in our project utilizes dataTables.js version 1.5.2 ...

Dealing with RxSwift observable errors interrupting the chain of events - Utilizing Rx for web services: strategies for

As a newcomer to RxSwift, I have extensively studied various documentations and talks but still feel like I am lacking some fundamental concepts. In my app, I encounter a challenge where the base URL of a RESTful web service is not known at build or start ...

Strip away double quotation marks from object attributes except those beginning with a number

I've searched extensively and reviewed various Q&A forums, but I haven't encountered a scenario quite like this. Here's an example of the object I'm working with: props: { "label": "1rem", "text3": "1rem", "text2Button": "1re ...

Retrieve data from the child window or obtain the uploaded file name

My issue involves a form that captures multiple entries and inserts them into a database via post data. This functionality works well. Additionally, I have a file upload form that effectively renames and moves files. However, my challenge lies in integrati ...

Exploring ways to extract complete information from a JSON array using JQuery

Seeking assistance on retrieving full JSON data records instead of just one. {"d":[{"__type":"Tolu+mirex_tbl_amsfile","SITEID":"366","ARRIVALAIRPORT":"","WAYBILLORIGINATOR":"","AIRLINEPREFIX":"","AWBSERIALNUMBER":"","HOUSEAWB":"","MASTERAWBINDICATOR":""," ...

What is the solution to removing the bottom margin from the jumbotron in the bootstrap framework?

I am building a website for my high school robotics team and I am new to HTML and CSS (bootstrap). I want to get rid of the gap between my banner and navbar on my site. Is there a way to remove that space? Check out our website: www.robotichive3774.com & ...

Utilizing nested dynamic attributes as grid columns within ExtJS applications

I recently experimented with the dynamic attributes approach in my prototype mongoDB application. This approach essentially structures data like this: { SKU: "Y32944EW", type: "shoes", attr: [ { "k": "manufacturer", "v": "ShoesForAll ...

Utilize JavaScript and jQuery to extract the selected text's context from a webpage

I'm looking to extract the contextual information surrounding a selected text on a web page, specifically the 25 words before and after it. I've tried using JavaScript and jQuery with the following code snippet but unfortunately, it doesn't ...

Stop a hyperlink from refreshing the webpage

Currently, I am in the process of developing a responsive menu. You can view a demo of my progress on Codepen. In order to prevent the page from reloading when I click a link within the menu, I have implemented the following JavaScript code: $('nav. ...

Using a variety of different font styles within a single sentence

I'm looking to add a title with text in one of my divs, but I want the title to be in 3 different font sizes. Any suggestions on how to achieve this without starting a new paragraph for each size change? Here's an example of what I'm trying ...

Adding a watermark to a PDF using ImageMagick's composite function while also enhancing the

I am trying to find ways to add a watermark to a PDF file. I have come across 2 solutions - using ghostscript and imagemagick composite. I found that ghostscript cannot be called from the command line, so I opted for the command 'composite' inste ...