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

Having trouble getting Vue async components to function properly with Webpack's hot module replacement feature

Currently, I am attempting to asynchronously load a component. Surprisingly, it functions perfectly in the production build but encounters issues during development. During development, I utilize hot module replacement and encounter an error in the console ...

Ensure that Angular resolver holds off until all images are loaded

Is there a way to make the resolver wait for images from the API before displaying the page in Angular? Currently, it displays the page first and then attempts to retrieve the post images. @Injectable() export class DataResolverService implements Resolv ...

Using the Match() function with an array of objects

I am working with an object array containing multiple variables. let Novels = []; class Novel { constructor(isbn, title, author, edition, publication, year) { this.isbn = isbn; this.title = title; this.author = author; this.publicat ...

Create a random number within a specified range using a different number in JavaScript

I am looking for a unique function that can generate a number within a specified range, based on a provided number. An example of the function would be: function getNumber(minimum, maximum, number) { ... } If I were to input: getNumber(0, 3, 12837623); ...

AJAX response from open cart is returning null JSON data

Hey there, I'm having a problem with my ajax request. It seems like I keep receiving a null value for json. Let me show you the JavaScript code... <script> $(document).ready( function() { $('#donate-box-submit').on('click' ...

Creating a dynamic className string in JavaScript with React

In my current project, I'm implementing mobile support by creating separate styles for desktop and mobile. Although most components are the same on both platforms, I have two .scss files dedicated to each. To apply the correct styles, I use a combina ...

Adjust the appearance of an element in a different parent when hovering over a specific element with a matching index

I have implemented a menu on my site in two different ways - one using text and the other using pictures. Users can click on both types of menus. Now, I am looking to create an interactive feature where hovering over a specific item in the text menu (such ...

Having trouble with radio button validation in JS?

I'm having difficulty understanding why the radio button is not staying checked when I select another option. To demonstrate, I created a fiddle where initially the "diy" button is selected but switching to "paid" causes the radio button to jump back ...

Using SVG files in NextJS

I'm encountering an issue while trying to import an SVG file in a NextJS project. The error message I keep getting is: ./assets/aboutimg.svg 1:0 Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type, ...

Rails is unable to store the JSON request as a parameter

I am attempting to save the token parameter that is received from a JSON request, but for some reason, I cannot confirm if it is actually being saved. My observation is that when a POST request with JSON parameters is made, Rails routes it to the create me ...

Development and staging setups tailored specifically for a JavaScript SDK

Currently, I am working with a Javascript SDK that is available on NPM. Alongside this, I have a Vue application utilizing the SDK and it's crucial for me to test them together across various pre-production environments (such as staging). Here are the ...

The state redirection feature in Ionic allows for nesting within a tab component,

Is there a way to ensure that the button in the contact tab redirects to “tabs.facts” properly? The following scenarios exist: .state('tabs.home', { url: "/home", views: { 'home-tab': { templateUrl: "templates/home.h ...

Is it possible to customize the CSS styles of a jQuery UI modal dialog box?

Having trouble with my CSS styles not applying to a dialog modal added to my website using jQuery UI, even when using '!important'. I suspect that the predefined jQuery or UI CSS styles from a CDN link are preventing me from overriding them. The ...

What could be causing the decrease in speed of my Three.js animation within Vue.js?

I attempted to replicate the impressive wave simulation from this CodePen link: https://codepen.io/cheekymonkey/pen/vMvYNV, using Vue.js. However, the animation seems to be running significantly slower when implemented in Vue.js. In my effort to recreate ...

Creating a Show/Hide toggle feature in AngularJS using NG-Repeat

I'm facing an issue with my code where I have a list of items that should only open one item at a time when clicked. However, currently, all items are opening on click and closing on the second click. Can anyone help me identify the problem in my code ...

Implementing a Collapse and Expand All feature within an Accordion Component

Hey there! I've been attempting to implement a Collapse All feature on my accordion but am having trouble figuring it out. The resource I've been referencing is this one. I've searched around and noticed that this accordion setup is a bit d ...

The appropriate method for transferring a prototype to an object

From my perspective, prototypes work like this: let Animal = function() { this.bark = "woof"; } Animal.prototype.barkLoud = function() { return this.bark.toUpperCase(); } let x = new Animal(); x.barkLoud() = "WOOF"; I f ...

Concealing a button once the collapse feature is toggled in Bootstrap

The following code snippet from the bootstrap website demonstrates how to use collapse functionality: <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Link with href & ...

Displaying text on hover and showing a text box when a link is clicked using CSS and JavaScript

Hovering over the text will display "Edit," and clicking on it will reveal a text box. This function will be used to update content using ajax. HTML: <table> <thead> <tr> <th> Name </th> <th> Age </th> ...

transfer information using dropzone

I am currently working with Dropzone and have implemented the following code: <form action="#" class="dropzone" ></form> Within the JavaScript code, the dropzone function is set to upload images only when a button with the id "startUpload" i ...