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

Dealing with multiple POST requests at once in Node Express JS - Best Practices

I've been working on a Node project with Express to handle incoming GET/POST requests. I have set up routes to manage various types of requests. One specific route, /api/twitter/search, calls a function that uses promises to retrieve Twitter feeds and ...

Having trouble finishing the npm installation process

Having trouble with completing 'npm install'. Can someone please assist me?</p> <pre><code>Encountering a warning about an old lockfile while running npm install. The package-lock.json file was created with an outdated version o ...

Retrieving JSON data in Perl

Struggling with accessing json values (translated from xml). foreach my $PORT (0..$#PORTS) { print Dumper $PORTS[$PORT]->{'neighbor'}; if (defined($PORTS[$PORT]->{'neighbor'}->{'wwn'}->{'$t'})) ...

Using JQuery to Load a CSHTML File into a Modal in C#

I am attempting to have the content of one specific page loaded into a modal on a different page when a button is clicked. Unfortunately, I am encountering an issue where not only the desired content from the specified page is loading, but also content fro ...

When trying to serialize elements from a form loaded by Firefox using AJAX, encountering difficulties due to

Visit the live version of this at . When prompted for a formId, input BroadRunTrack2013. Follow by adding an item to cart and entering player name information (you can use random data for now). Select the Runner's Hat, choose color/size, specify quant ...

The function Mediarecorder.start() is experiencing issues on Firefox for Android and is not functioning

Recently, I've been facing a peculiar issue while developing a web application. The purpose of this app is to capture about 10 seconds of video intermittently from the device webcam and then upload it to a server. For this functionality, I utilized th ...

What is the best way to access external value in an Angular directive?

check out this plunker link. HTML: <body ng-app="app"> <h1>selectable</h1> <selectable text="link1" status="true"></selectable> <selectable text="link2" status="false"></selectable> <p> ...

Comparing Optimistic Updates and Tag Invalidation in RTK Query

I found a basic code example from the RTK query documentation: updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({ query: ({ id, ...patch }) => ({ url: `posts/${id}`, method: 'PUT', ...

Discover the optimal approach for merging two jQuery functions effortlessly

The initial function (which can be accessed at ) is as follows: $('#confirm').confirm( { msg: 'Before deleting a gallery and all associated images, are you sure?<br>', buttons: { separator: ' - ' } } ); ...

Avoid repeatedly invoking an API within a loop

Is there a way to continuously call an API every 2 seconds within a loop? var itemArray = ['apple', 'banana', 'orange']; for (var i = 0; i < itemArray.length; i++) { $timeout(makeApiCall(itemArray[i]), 2000); } functi ...

Parsing JSON into a POCO object using the Contentful .NET SDK encounters a Newtonsoft.Json.JsonReaderException

Update 1 8.July.2020: Beginning with the Rich Text field type may not have been the best choice, as it appears to require additional effort to access properly: Update 2 9.July.2020: The serialization of Rich Text to a string seems challenging due to the w ...

Using the Count() function in PHP to update information upon page refresh

I have created a basic cart that displays a div containing purchased items when hovered over. The issue I am facing is that every time I click on the add to cart button, it doesn't immediately update the number of items in the cart. I have to manually ...

Retrieve JSON information from an asmx file using a C# webpage

I'm working with code that looks like this: [ScriptService] public class Titles : WebService { List<Title> Title = new List<Title>(); SqlConnection connection; SqlCommand command; SqlDataReader reader; [WebMethod()] ...

How to add and append values to an array in a Realtime Database

My React.js app allows users to upload songs to Firebase and view the queue of uploaded songs in order. The queue can be sorted using a drag-and-drop system that updates the database in Firebase. Is there a way to insert these songs into an array when uplo ...

Influencing location preferences in Google's place search

I'm currently implementing a Google Places search feature and I need to enable "Location Biasing" for the GCC countries (UAE, Saudi Arabia, Oman, Kuwait & Bahrain). My goal is to achieve the functionality described in the following link: https://deve ...

Incorporating a CSS stylesheet into the theme settings of the Stratus 2 Beta platform

I have been attempting to personalize my Stratus 2 Beta by implementing a custom theme. I created a separate CSS file named "stratus.css" and stored it in the CSS directory of my website - with the CSS code being identical to this example. Below is my Jav ...

XMLHttpRequest response: the connection has been terminated

After developing a Flickr search engine, I encountered an issue where the call to the public feed or FlickrApi varies depending on the selection made in a drop-down box. The JSONP function calls provide examples of the returned data: a) jsonFlickrApi({"ph ...

Having trouble retrieving the JSON value as it returns undefined

Having trouble extracting specific values from JSON data. I'm trying to retrieve the value of result.datafeed[0].prod[0].vertical[0].deviceProductJson[0].product_brand, but it keeps returning as undefined. To investigate further, I examined the stru ...

Setting up Jest

I'm currently attempting to integrate the Jest Testing framework into my React Native project. Unfortunately, I am encountering an error message: Failed to retrieve mock metadata: /Users/me/Documents/Development/project/node_modules/global/window.js ...

Differences: Angular ngController vs Controller embedded in Directive

I'm interested in exploring the various scenarios where these two methods of creating a controller can be used: Using ngController: myApp.controller('myController', ['$scope', function ( $scope ) { }]); Creating the controller ...