Accessing Google Maps using latitude and longitude coordinates from a Json file

I am having trouble displaying markers on the map when trying to open it with latitude and longitude from a Json file. The map is opening, but the markers are not showing up.

Currently, I am fetching a Json file using PHP, creating a variable array, and then passing this array to JavaScript with the latitude and longitude coordinates. However, the markers are not being displayed on the map.

Does anyone have any idea what might be causing this issue? Below is the code I am using.

file Points.Json

{
"points":[
            {
                "id"        :"01",
                "name"      :"marker01",
                "latitude"  :"-23.538241",
                "longitude" :"-46.647703"
            },
            {
                "id"        :"02",
                "name"      :"marker02",
                "latitude"  :"-23.551258",
                "longitude" :"-46.656243"
            },
            {
                "id"        :"03",
                "name"      :"marker03",
                "latitude"  :"-23.559160",
                "longitude" :"-46.624443"
            }
        ]
  }

<?php 
  $fileJson = file_get_contents('points.json');
  $fileJson = json_decode($fileJson);

  foreach ($fileJson->points as $value) {
    $locations[] = array('id'=>$value->id, 'name'=>$value->name, 
    'latitude'=>$value->latitude, 'longitude'=>$value->longitude);
  }
    $locations = json_encode($locations);
  ?>

  <div id="map"></div>

function initMap() {
  var mapOptions = {
    center: new google.maps.LatLng(-23.538241, -46.647703),
    zoom: 12,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var myMap = new google.maps.Map(document.getElementById("map"), mapOptions);

var locationdata = '{"locations":<?php echo $locations; ?>}';

  var locations = [];
  var markers = [];
  for (var i = 0; i < locationdata.locations.length; i++) {
    var marker_location = locationdata.locations;
    createMarker(marker_location[i],markers,myMap);
  }
  var markerCluster = new MarkerClusterer(myMap, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
  });
}

initMap();

function createMarker(marker_location, markers, myMap) {
    var latLng = new google.maps.LatLng(marker_location.latitude, marker_location.longitude);
    var marker = new google.maps.Marker({
      'position': latLng,
      map:map,
      icon: "http://maps.google.com/mapfiles/ms/icons/green.png"
    });
    markers.push(marker);

    var i_box = '<div>nome :'+ marker_location.nome +'<br>Latitude :' + marker_location.latitude + '<br>Longitude :' + marker_location.longitude + '</div>';

    var myOptions = {
      content: i_box,
      disableAutoPan: false,
      maxWidth: 0,
      pixelOffset: new google.maps.Size(-100, -100),
      zIndex: null,
      boxStyle: {
        background: "url('tipbox.gif') no-repeat",
        opacity: 1,
        width: "200px"
      },
      closeBoxMargin: "0px 0px 0px 0px",
      closeBoxURL: "https://www.google.com/intl/en_us/mapfiles/close.gif",
      infoBoxClearance: new google.maps.Size(1, 1),
      isHidden: false,
      pane: "floatPane",
      enableEventPropagation: false
    };

    google.maps.event.addListener(marker, "click", function(e) {
      ib.open(myMap, this);
    });
    var ib = new InfoBox(myOptions);
}
body{
margin: 0;
padding: 0;
background: #fafafa;
font-size: 13px;
font-family: 'Helvetica Neue',sans-serif;
color: #454545;
line-height: 15px;}


#maps{height:400px;width:100%;background:#ddd;}
#maps img{max-width:inherit}


#map{height:400px;width:100%;background:#ddd;}
#map img{max-width:inherit}
<div id="map"></div>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBox3TvUA_j5u4bDmVLXvbtzO7F6y19piA&callback=initMap" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Answer №1

If you're looking for a detailed example of what you're trying to accomplish, check out this resource: https://developers.google.com/maps/documentation/javascript/datalayer

For any future problems, it's a good idea to refer to the examples provided on the Google Maps API website. These examples offer clear instructions and can be very helpful.

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

Changing a string into a JavaScript date object

I am encountering an issue where I have a string retrieved from a JSON object and attempting to convert it to a JavaScript date variable. However, every time I try this, it returns an invalid date. Any insights into why this might be happening? jsonObj["d ...

Dealing with timeout errors when using Puppeteer's page.waitForNavigation()

When using puppeteer, I initiate a page by entering a value and it displays the resulting output. await page.click('button[class="button form-button rs-gcbalance-btn"]') await page.waitForSelector('div[class="small-4 large-4 rs-gcbalance-r ...

Encountering a Module node browserify issue

I recently attempted to utilize the Dyson module node from https://github.com/webpro/dyson#installation. However, upon executing the 'dyson' command, I encountered the following error in my terminal. $ dyson Prueba/ module.js:491 throw err ...

The functionality of AJAX is successful when tested on a local server, but encounters issues when deployed on a live

While the following code functions correctly on localhost, it fails to work on the live server. IMPORTANT UPDATE: There's only 1 issue remaining: Upon successful execution of this AJAX block: $(".FixedDiv").addClass("panel-danger"); setTimeout(c ...

What is the technique to make a *ngFor render items in a random order?

I'm working on creating an application that needs to display elements in a random order. However, due to restrictions within the application, I am unable to modify the ngFor directive. How can I achieve displaying ngFor content randomly? ...

Issue with deleting and updating users in a Koa application

My goal is to create a function that deletes a specific user based on their ID, but the issue I'm facing is that it ends up deleting all users in the list. When I send a GET request using Postman, it returns an empty array. What am I doing wrong? I do ...

Unable to retrieve uploaded files within the controller

Update with the latest code that helps solve my problem $scope.uploadedFiles = []; $scope.upload = function(files) { $scope.uploadedFiles = files; angular.forEach(files, function(file) { if (file && !file.$error) { ...

Discover the method for storing multiple values in local storage using a dictionary with JavaScript

I have a scenario in my code where I need to update a value without storing a new one. Let's say I need to input values in the following format: { firstname:'kuldeep', lastname:- 'patel' } After entering the values, they g ...

What are the steps for implementing Babel in a CLI program?

Currently, I am working on developing a CLI program in Node using Babel. While researching, I came across a question on Stack Overflow where user loganfsmyth recommended: Ideally you'd precompile before distributing your package. Following this ad ...

transferring information between two ajax calls upon completion of the first ajax request

Attempting to pass data to jvectormap from an ajax call, using a when function to ensure the code runs after the ajax call has finished loading. The issue I'm facing is that the map appears empty and I encounter an error. Uncaught ReferenceError: ...

Potential dangers involved in sending HTML content through an AJAX request over a secure HTTPS connection

I am exploring the idea of dynamically loading HTML content, such as updating a Bootstrap modal dialog's contents using AJAX calls instead of refreshing the entire page. However, before I proceed, I want to understand the potential risks involved and ...

Instructions on extracting a random element from an array and continue removing elements from the array until it is completely empty

I am attempting to utilize either jquery or javascript to remove a random item from an array until it is empty. Each time I remove an item, I want to log it to the console. My goal is to create elements with random images from the specified array until all ...

Adjust the height of a DIV element using Jquery Resizable to a minimum height of 1px, smaller than its default value

Having an issue with the Jquery UI Resizable functionality. I've implemented Jquery resizable to adjust a div's width and height dynamically. It's been working well, but I'm encountering a problem when attempting to decrease the height ...

Serving static files in Next.js with specific extensions without triggering a download

I'm facing an issue where I need to serve the stellar.toml file in domain/.well-known/stellar.toml with the content type as text/plain. The current configuration works only when the stellar file is saved without an extension. It is essential for me t ...

Steps to invoke the ansible playbook in a recursive manner according to a specific loop condition

Can anyone provide me with a solution for executing a playbook recursively until a specific condition is met? I have been struggling to achieve this and would appreciate any help. Ansible-version: 2.2.1.0 Below are the details of my test plays: Main_pla ...

Looking for a solution to dynamically fill a list in JQuery with data from a JSON file. Any suggestions for troubleshooting?

Currently, I am utilizing a JSON file to fetch Quiz questions. In my approach, each question is being stored in an array as an object. The structure of the question object includes 'text' (the actual question), 'choices' (an array of po ...

Add CSS styling to a section of a canvas

I want to use a specific cursor png for just a portion of a canvas. Currently, I have code that applies the cursor to the entire canvas like so: .myClass { cursor: url('../img/myCursor.png') 7 33, auto; /* img hotspot centred*/ } However, I ...

Issue with TypeORM Many-to-Many relation returning incorrect data when using the "where" clause

I'm facing an issue with my database tables - User and Race. The relationship between them is set as Many to Many , where a Race can have multiple Users associated with it. My goal is to retrieve all the Races that a particular user is a member of. Ho ...

What is the best way to extract the JSON data from a client-side GET request response?

Here is my request from the client side to the server in order to retrieve JSON data. fetch("/" + "?foo=bar", { method: "GET", }).then(response => { console.log(" ...

Preventing page refresh with Javascript when clicking on CAPTCHA

I have been exploring a CAPTCHA tutorial on TutsPlus.com and I am facing an issue where the 'Incorrect Captcha message' keeps appearing, indicating that my user input through $_POST does not match the stored $_SESSION string. Upon investigating ...