Showcasing external API JSON data on Google Maps

My goal is to integrate remote API JSON data into Google Maps. Currently, my code successfully works with local JSON data that is within the same script. However, I want to populate the Google Map with remote API JSON data. I am using AngularJS Google Maps integration for this purpose. The code functions perfectly when referencing JSON data from the script where Google Maps is implemented locally. But now, I need to populate the Google Maps with JSON from an external source (remote JSON). Any advice on how to achieve this? Below is a snippet of my code:



  var points = this;
  points.testData = [];

  $http({
    method: 'GET',
    url: 'https://api.jsonbin.io/b/61361f26dfe0cf16eb55fd9f',
  })

  .then(function successCallback(response) {
        console.log("success,", response);
        $scope.testData = response.data;

    }, function errorCallback(response) {
      console.log("failure,", response);
    });


  // GOOGLE MAPS CODE
  $scope.highlighters = [];
  $scope.gMap = null;

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

  var googleMapOption = {
    zoom: 2,
    center: new google.maps.LatLng(2.8, -187.3),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };


  $scope.gMap = new google.maps.Map(document.getElementById('googleMap'), googleMapOption);

  var createHighlighter = function(city) {

    var cityInfo = new google.maps.Marker({
      map: $scope.gMap,
      position: new google.maps.LatLng(city.attributes.coordinates.lat, city.attributes.coordinates.lng),
      title: city.attributes.name
    });

    cityInfo.content = '<div>' + city.attributes.address1 + '</div>' +
    '<div>' + city.attributes.openingHours + '</div>';

    google.maps.event.addListener(cityInfo, 'click', function() {
      winInfo.setContent('<h1>' + cityInfo.title + '</h1>' + cityInfo.content);
      winInfo.open($scope.gMap, cityInfo);
    });
    $scope.highlighters.push(cityInfo);
  };

  for (var i = 0; i < testData.length; i++) {
    createHighlighter(testData[i]);
  }

This is my JSON file


var cities = [{
          "attributes": {
              "name": "Test1",
              "city": "Mthatha",
              "address1": "Cnr Sisson and Sutherland Road",
              "coordinates": {
                  "lng": 28.7648433,
                  "lat": -31.5805384
              },
              "openingHours": "Mon-Fri: 8am-6pm, Sat-Sun: 8am-5pm"
          },
             "attributes": {
              "name": "Test2",
              "city": "Mthatha",
              "address1": "Cnr Sisson and Sutherland Road",
              "coordinates": {
                  "lng": 28.7648433,
                  "lat": -31.5805384
              },
              "openingHours": "Mon-Fri: 8am-6pm, Sat-Sun: 8am-5pm"
          }];

Answer №1

After moving the for loop into the .thenFunction(), I was able to successfully resolve the problem.

Appreciate all the helpful feedback provided in the comments!

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

"Patience is key as we await the resolution of a promise within the confines of an emitter

My goal is to wait for the promise to be resolved before continuing when the someevent event is fired. However, even though I use a then in my code snippet below, it seems that the process shuts down before the slowFunctionThatReturnsPromise is resolved, ...

Having trouble with sending an Incoming Slack hook message using Angular1's $http method

Here's the http request code snippet I'm using: $http({ method: 'post', dataType: 'json', data: { 'username': 'HiBye', 'icon_emoji': ':ghost:', 'channel': &a ...

My changes to the HTML file are not being reflected in the browser, even after clearing the cache. This is happening in an Angular and Node.js application

I'm currently developing an application using Angular and Node.js. I've noticed that when I make changes to the HTML file, the browser isn't updating even after clearing the cache. Could this be a coding issue? Any suggestions on how to fix ...

I encountered a NextJS error while trying to implement getStaticProps(). Can someone help identify the issue at hand?

I'm encountering an issue while using getStaticProps(). I am working with nextjs and passing the returned value as props to a component. Despite trying various methods such as await and JSON.stringify(), nothing seems to be effective in resolving the ...

Obtain a collection of information from a web API by utilizing jQuery

Click on the following link to access live data from a web API: This is my first attempt at retrieving data from an API, so I may have missed some settings. To test the connection with the API, I included the following code in the HTML page: <div id= ...

Resolving Angular Issue: Error code (5, 12) TS2314 - Solving the requirement for 1 type argument in the 'Array<T>' generic type

Encountered an issue in the JSON data within my typescript file. I'm working on creating an Angular API that performs a git-search operation. Initially, I had the JSON data set up correctly but then I modified all data values to their respective data ...

What is the best way to store client-uploaded files on the client-side using Bootstrap forms and Express server code?

Essentially, the user submits a file for upload, which is then saved on the client-side (I believe this is handled by PHP), and the upload form I am utilizing is a Bootstrap HTML form. On the server side, I am writing my code with Express. I'm feeling ...

A guide to displaying numerous notifications using notistack in a React environment

I'm currently experimenting with React's 'notistack' module to showcase multiple notifications as a stack. However, it seems like I might be making an error since every time I encounter a warning: react_devtools_backend.js:3973 Warning ...

Exploring the process of obtaining a URL using getStaticPaths in Next.js

I am facing difficulty getting the URL in getStaticPath export const getStaticPaths = async (props) => { if (url === 'blah') { return { paths: [ { params: { pid: "create" } }, ], fallback: true, }; ...

I am unable to engage with an element encapsulated within a #shadow-root that includes an <iframe> element

Original page source: Currently utilizing selenium with Java for web automation. In order to reach the shadow-root, I am utilizing JavaScriptExecutor (document.shadowRoot.querySelector) Successfully able to interact with various elements within the page ...

Difficulty encountered while implementing mouseover event listener for an SVG component

I'm having trouble triggering an event for an svg element. Here's the link to my jsfiddle example: https://jsfiddle.net/r1ahq5sa/ Here's the HTML code: <div class="row"> <div class="col-md-8"> <svg class="video-nav-bar ...

The sequence of execution in the code is not as anticipated

JS <script type="application/javascript"> var app = angular.module("app", []); app.controller("AppCtrl", function ($scope, $http) { $scope.data = []; $http.get("{{ url_for('data') }}") ...

The CORS policy has blocked access to XMLHttpRequest from 'localhost' to 'localhost'. A preflight response is required

I'm encountering the following error message: Access to XMLHttpRequest at 'https://localhost:44355/Brand' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access ...

Is there a way for me to determine if a domain has been registered by the client?

I'm interested in creating a Web app that allows users to enter a domain name and then uses JavaScript to check its availability. I'm wondering if there's a method to do this without relying on my own hosting server. Is it possible to send a ...

Tips on updating the $authProvider.loginUrl for Satellizer from an Angular controller

Consider this hypothetical situation: A user attempts to access a /settings page without being logged in. The Settings controller detects based on $auth.isAuthenticated() != true that the user is not logged in, and directs them to the /login page. The us ...

Resolving Typescript custom path problem: module missing

While working on my TypeScript project with Express.js, I decided to customize the paths in my express tsconfig.json file. I followed this setup: https://i.stack.imgur.com/zhRpk.png Next, I proceeded to import my files using absolute custom paths without ...

Creating a dynamic link in Vue JS is a cinch!

I currently have the following code snippet: <b-dropdown text="Select Factory" block variant="primary" class="m-2" menu-class="w-100"> <b-dropdown-item @click="selectedFactory='China'"> ...

Obtaining the current URL using Angular within a Ruby on Rails application

I am working on a Rails app that integrates AngularJS. When I'm on a URL like "/items/3", how can I access the ID (in this case, 3) from within the Angular controller? I have attempted using: $location.url() However, I encountered the following er ...

invoking an API within a map function and utilizing the response

vm.owners = parents.children.map(function(e) { getparentById(e.Id) .then(function(getresponse) { var parentLink = '<a href="/#/parent/onboard/' + e.Id + '" target="_blank">' + e.Number + "-&qu ...

Use CSS media queries to swap out the map for an embedded image

Looking to make a change on my index page - swapping out a long Google Map for an embedded image version on mobile. The map displays fine on desktop, but on mobile it's too lengthy and makes scrolling difficult. I already adjusted the JS setting to "s ...