Utilize dynamic Google Maps markers in Angular by incorporating HTTP requests

Struggling to find a solution for this issue, but it seems like it should be simple enough. Initially, I fetch my JSON data using the code snippet below:

testApp.controller("cat0Controller", function($scope, $http){

var url = "../../../Data/JSONs/randomdata_cat0.json";
$http.get(url).then(function(response){
    $scope.dataset = response.data;
    $scope.hi = response.status;
});
});

Successfully displaying the JSON data in an HTML table using ng-repeat.

The structure of the JSON data is as follows:

[
 {
   "Lat": 16.374,
   "Long": 48.212,
   "Timestamp": "2017-01-07 / 13:31:56",
   "Downstream": 20.79852450876752,
   "Upstream": 20.87613636972708,
   "Category": 5
 },

Now the goal is to extract the Latitude and Longitude values from the JSON and place Google Maps markers at those positions with onClick text showing Upstream, Downstream, and timestamp.

Below is my current HTML and Google Maps implementation:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
      <script src="../js/speedtestTestController.js"></script>

      <style type="text/css">
          html { height: 50% }
          body { height: 100%; margin: 0; padding: 0 }
          #map_canvas { height: 40%; width: 40%; }
      </style>


      <script type="text/javascript">

          // Google Maps initialization functions

      </script>




      </head>
  <body ng-app="testApp" >

  <div id="map_canvas" style="width:100%; height:100%"></div>



  </body>
    </html>

If you have any insights on how to dynamically generate these markers from the JSON data, your help would be greatly appreciated!

Thank you!

Answer №1

Check out this example showcasing how to retrieve marker data from a JSON file and showcase it on a map:

angular.module('mapApp', [])

    .controller("mapCtrl", function ($scope, $http) {
        $scope.loadData = function () {
            var url = "https://gist.githubusercontent.com/vgrem/4c3db2767a4345e2f7b0ee711c38097d/raw/data.json";
            return $http.get(url).then(function (response) {
                return response.data;
            });
        };


        $scope.initMap = function (data) {
            var mapOptions = {
                zoom: 4,
                center: new google.maps.LatLng(48.209500, 16.370691),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            data.forEach(function (item) {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(item.Lat, item.Lng),
                    animation: google.maps.Animation.Bounce,
                    map: map
                });

            });
        };


        $scope.loadData()
            .then($scope.initMap);

    });
#map_canvas { 
    height: 420px; 
    width: 100%; 
}
<script src="https://maps.google.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="mapApp" ng-controller="mapCtrl">
  <div id="map_canvas"></div>
</div>

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

Choosing an option from a dropdown menu by extracting information from JSON content

My goal is to develop a basic jQuery plugin that interacts with a geolocation system to provide data on the location of the user's IP address and then automatically select the corresponding country in an HTML form. Within my HTML code, I have a selec ...

What is the most efficient way to move queried information from one table to another while maintaining all data entries?

Currently, I am working on a small POS project. In this project, I have two tables. The main purpose of the first table is to retrieve products from a search box with two column names retrieved from the database. If the products are found, I want to be abl ...

Can the height of one div be determined by the height of another div?

Here's the specific situation I am facing: I want the height of Div2 to adjust based on the content of Div3, and the height of Div3 to adapt based on the content in Div2. The height of Div1 is fixed at 500px. Some of the questions that arise are: I ...

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

The JS content failed to load into the HTML page

I need help creating a workout tracker using two JS files. The main.js file is responsible for loading content from the second file (workoutTracker.js) into the index.html. However, I'm facing an issue where the content is not being displayed on the p ...

Error in Uploading Files with AngularJS - Uncaught SyntaxError: Unexpected token

I'm having trouble uploading an image file using Angular and PHP, specifically at the app.service Error line: app.service('fileUpload', ['$https:', function ($https:) { Code app.service('fileUpload', ['$https:&ap ...

Is there a way to update a single element within an array without triggering a refresh of the entire array?

Is there a way to prevent the component from rerendering every time new data is input? I attempted to memoize each cell but I am still facing the same issue. Any suggestions on how to accomplish this? import React, { useState, memo } from "react&quo ...

JavaScript's menu button has a callback function assigned to it

The definition can be found below. var CMenu = cc.Sprite.extend({ onClickCallback: null, onClick: function (callback) { this.onClickCallback = callback; }, handleTouches: function (touch, evt) { (this.hovered && this.onClickCallback) &am ...

Prevent the upward arrow from appearing on the first row and the downward arrow from appearing on the last row when

This is a straightforward question, but I'm unsure how to achieve it. I am currently working on sorting columns using jQuery. $(document).ready(function(){ $(".up,.down,.top,.bottom").click(function(){ var row = $(this).parents("tr:f ...

Alternatives to socket.removeAllListeners(); for client-side operations

I recently encountered a challenge similar to the one discussed in the thread Enhancing this AngularJS factory for compatibility with socket.io. However, the solution provided seems to reference a function that is no longer supported. Can anyone advise o ...

The multiArr.shift() operation is throwing a TypeError: The function shift cannot be located in the SN object

As a beginner in Java app development, I am currently attempting to export JSON from a Google spreadsheet. While watching a tutorial, I came across the following code: function doGet(){ var result ={}; var sheet1 = SpreadsheetApp.getActiveSpread ...

Array's Javascript length of 0

I have encountered some strange behavior with the following code. It's displaying an array length of 0 even though I can see a length greater than 0 when printing it right before that: var getTopSelection = function(callback) { var topSelection = ...

What is the best way to extract parameters from a JSON file using Python and convert them into a string

As a newcomer to Python, I am currently experimenting with reading parameters from a JSON file and using them as arguments in a command via the os.system module in Python. The code snippet I have written so far is as follows: import json jdata = open(&ap ...

Determine whether the elements within an array are present on the webpage. If they are, display an alert. If not, reload the page

Initially, I had a userscript designed to search for a specific string within a webpage. If the script failed to locate the string, it would refresh the page after 4 seconds: var item = 'apple'; if(document.body.innerHTML.toString().indexOf(item ...

Instructions for transforming rows into columns in JSON format

Looking to convert an array of JSON objects into a format where rows become columns and the values at the side become column values, similar to the crosstab function in PostgreSQL. The JSON data looks something like this: {"marketcode":"01","size":"8,5", ...

The init function of the controller in Ext JS version 4.1.0 is not being executed

Recently, I started learning javascript and extjs, and while following the extjs 4.1 MVC Architecture tutorial, I ran into an issue. Everything was working fine initially, but when I tried to add the controller to the application, something went wrong. Bot ...

Assign the ng-repeat item to a variable in the controller's scope

Can anyone help me figure out how to pass a particular item from my view to a function in my controller? Here is the code: The view where I want to pass p.id <tr ng-repeat=" p in projetsListe"> <td>{{p.NomProjet}}</td> <td>{{c ...

Navigating through JSON data in an Angular application

I am currently facing an issue with uploading and parsing a JSON file in my Angular application. The problem lies in the fact that even though I can successfully upload the file, I am unable to access the data from it. To ensure the correct file is being ...

What steps should I take to fix the TypeScript Compiler issue "Global member 'NodeJS' has no exported namespace 'Global'?"

QUERY: What steps should I take to fix the Typescript Compiler (tsc) error stating "Namespace 'NodeJS' has no exported member 'Global'"? Upon executing tsc, this particular error unexpectedly appeared in a project that is considered "l ...

How to break out of an endless loop in Node.js and Express.Js

I have developed an Express app that is designed to paginate through an external API call. I have thoroughly examined the code but for some reason, the loop condition to break the function isn't being triggered. Any assistance on this matter would be ...