Attempting to extract data from an external JSON file in order to dynamically generate markers for the Google Maps API

Using JavaScript and an external JSON file, I have the JSON data stored in a file named csus_locations.JSON within the same folder as my js file. Here is a snippet of the JSON data:

{
 "locations": [
 {
    "latitude": 38.558961, 
    "longitude": -121.423011,
    "name": "AIRC",
    "title": "THIS IS WHERE STUFF GETS DONE!"
  },
{
    "latitude": 38.562605, 
    "longitude": -121.419683,
    "name": "GUY WEST",
    "title": "PRESIDENT?"
},
{
    "latitude": 38.556652, 
    "longitude": -121.423842,
    "name": "well",
    "title": "WORKOUT"
  },
{
    "latitude": 38.555465, 
    "longitude": -121.422551,
    "name": "Hornetsatdium",
    "title": "FOOTBAL!"
}

]}

The JSON code is confirmed to be valid, but I'm considering simplifying it for easier parsing into Google Maps by removing "locations" and brackets.

I've attempted to parse the JSON file using $http.get, but I'm uncertain about the correctness of my code.

angular.module('app.controllers', ['ionic']) 

.controller('mapCtrl', function ($scope, $ionicSideMenuDelegate, $ionicLoading, $compile, $ionicPopup, $http) {

    $ionicSideMenuDelegate.canDragContent(false);

    var myLatlng = new google.maps.LatLng(38.5602, -121.4241);

    var mapOptions = {
        center: myLatlng,
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoomControl: false,
        disableDefaultUI: true
    };

    var map = new google.maps.Map(document.getElementById("map"),
        mapOptions);

    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: 'Sac State'
    });

    // Attempting to parse with $http.get, unsure if the code is correct
    $http.get('csus_locations.json').success(function(res){
        console.log("success!");
        $scope.locations = res.locations;
        
        var latLng_csus = new google.maps.LatLng(value.latitude, value.longitude);
        var marker = new google.maps.Marker({
            position: latLng_csus,
            title: value.name
        });

    });

    var onSuccess = function (position) {
       
        // Marker + infowindow + angularjs compiled ng-click
        var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
        var compiled = $compile(contentString)($scope);

        var infowindow = new google.maps.InfoWindow({
            content: compiled[0]
        });

        marker.setPosition(
            new google.maps.LatLng(
                position.coords.latitude,
                position.coords.longitude)
        );

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });

        $scope.map = map;

    };

    function onError(error) {
        alert('code: ' + error.code + '\n' +
              'message: ' + error.message + '\n');
    }

    navigator.geolocation.watchPosition(onSuccess, onError, {
        maximumAge: 3000,
        timeout: 5000,
        enableHighAccuracy: true
    });

});

Answer №1

The JSON file provided has been confirmed to be valid, allowing for the initialization of markers as shown below:

$http.get('csus_locations.json').success(function (data) {
    $scope.locations = data.locations;

    $scope.locations.forEach(function(item){

        var latLng = new google.maps.LatLng(item.latitude, item.longitude);
        var marker = new google.maps.Marker({
           position: latLng,
           title: item.name,
           map: map
        });

    });

});

See a working example below

angular.module('mapApp', ['ionic'])

.controller('mapCtrl', function ($scope, $http) {

    var mapOptions = {
        center: new google.maps.LatLng(38.5602, -121.4241),
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoomControl: false,
        disableDefaultUI: true
    };

    var map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);

 
    $http.get('https://gist.githubusercontent.com/vgrem/c7ec78e7078c2c9ed1c3/raw/959e9d8b8e60544fcc169ea890e84a2624ed8bbb/csus_locations.json').success(function (data) {
        $scope.locations = data.locations;

        $scope.locations.forEach(function(item){

            var latLng = new google.maps.LatLng(item.latitude, item.longitude);
            var marker = new google.maps.Marker({
               position: latLng,
               title: item.name,
               map: map
            });
           
        });
        
    });

});
#map-canvas {
    width: 800px;
    height: 600px;
}
<link href="http://code.ionicframework.com/1.1.1/css/ionic.css" rel="stylesheet">
<script src="http://code.ionicframework.com/1.1.1/js/ionic.bundle.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=&v=3.0&sensor=true"></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

What is the process for generating an attribute in a system?

If I want to create an element using plain JavaScript, here is how I can do it: var btn = document.createElement('button'); btn.setAttribute('onClick', 'console.log(\'click\')'); document.body.appendChild( ...

Subsequent calls to React's setState with an array are causing duplicate items to be appended twice

While developing a simple Twitter clone using React, I encountered a strange issue when adding a new tweet. Currently, I store a tweets array locally using the useState hook and employ setState to insert the new tweet into the array. Initially, everything ...

The Challenge of Using the "this" Keyword in ReactJS Functional Components

I couldn't find any answers to my specific question. I want to know how to convert the "this" keyword into a React functional component in the following situation: <SimpleStorage parent={this}/>. This component is part of a library (called react ...

What could be causing the if statement to evaluate as false even though the div's style.display is set to 'block'?

Building a react application using createreactapp and encountering an issue with an if statement that checks the CSS display property of a div identified as step1: const step1 = document.getElementById("step-1") if (step1.style.display === 'blo ...

issue with custom cors policy implementation

I have a unique custom CORS policy implementation shown below, in which I explicitly set support-credentials to false: public class CorsProviderFactory : ICorsPolicyProviderFactory { //https://msdn.microsoft.com/en-us/magazine/dn532203.aspx publi ...

Exporting files to the www folder during Ionic 5 build process

I have a project in progress for developing an application that will cater to multiple companies. Each company would require its own customized app with unique environment variables. To achieve this, I have created "env.js" files specific to each company, ...

Tips for showing an Object with nested Objects in Vue.js

Looking for guidance on displaying a JSON object in Vue.js with the following structure: { "1": [ "15-16", "16-17", "17-18", "18-19" ], "2": [ & ...

The upload directory in KCFinder can be accessed and selected using a URL

Issue: While using the link to open kcfinder as defined in kcfinder, I encountered a problem. The link is intended to open kcfinder with the provided parameters: window.open('/kcfinder/browse.php?type=files&dir=files/public&subDi ...

When a specific item is selected from a drop-down menu, text boxes and drop-downs will dynamically appear and change

In the current version of my code, there is a single drop-down menu with three options for the user to select from. If "Complete" is chosen, a text box should appear. If "Abandon" or "Transfer" is selected, a separate drop-down menu needs to be displayed. ...

Generate a fresh JSON object by adjusting JSON data in Angular 6

Here is a sample JSON structure: [ { "Key": "doc/1996-78/ERROR-doc-20200103.xlsx" } }, { "Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx" }, { "Key": "doc/1996-78/PENDING-doc-20200103.xlsx" } ] I need to split the values of the K ...

Interactive Communication: PHP and JQuery Messaging Platform

I am developing a social networking platform and I am looking to integrate a chat feature. Currently, I have a home.php page that displays a list of friends. The friends list is loaded dynamically using jQuery and PHP, like this: function LoadList() { ...

The error message "gaq is not defined in opencart 2.0" indicates

While attempting to monitor transactions in OpenCart, I encountered the following error message: Uncaught ReferenceError: _gaq is not defined(anonymous function) This is the method I am using for tracking in my catalog/view/theme/default/template/commo ...

Utilize AJAX JQuery to Transmit POST Data

I am facing an issue with sending the selected item from a Bootstrap dropdown to my controller using the POST method. Unfortunately, I am encountering difficulties in getting it to work. Within the dropdown, I am fetching records from the database and dis ...

I am experiencing an issue where my React application is not loading the fonts when utilizing `type: 'asset/resource'` to load fonts within a CSS file. Can anyone provide guidance on

I'm encountering an issue with my webpack setup where fonts are not being loaded when using type: 'asset/resource'. Actually, there are several problems arising from the use of asset/resource, but let's focus on this particular issue fo ...

Passing PHP data through AJAX to a JSON object and displaying it in

I've been making progress with the Ajax method, but I keep encountering some minor issues along the way. One problem I'm facing is trying to implement a display-comment functionality. When the user clicks on a link, I want a modal window to open ...

Issues with Angular updating the *ngFor Loop

I'm looking to showcase a lineup of upcoming concerts in my HTML, sourced from a web API (which is functioning correctly). The API is encapsulated within a ConcertService: @Injectable({ providedIn: 'root' }) export class ConcertService { ...

Verify the accuracy of the properties received from mapStateToProps in a functional React Redux component

I am working with 3 components: TypeList, ConnectedType (connected through connect(mapStateToProps)(Type)), and the component Type. Type will receive props from both TypeList (onClick, name) passing props to ConnectedType as well as ConnectedType's ma ...

Dynamically load the configuration for a JQuery plugin

Currently, I am utilizing a JQuery plugin from this source. My goal is to dynamically load the configuration of the plugin without directly modifying it within the plugin file. Below are the default options provided by the plugin: $.Slitslider.def ...

Update the value of a JSF managed bean property for a h:SelectOneMenu using JavaScript

Hello, I have a unique method of injecting HTML code at runtime into my web page using JavaScript. The specific piece of code that I am cloning and inserting is as follows: <div id="any"> <h:selectOneMenu value="#{browserOSList.browserXP[0]}" ...

What is causing my button to act in this way?

Initially, the website redirects to an undefined URL and then to test.com. I am looking for a way to implement a redirection sequence from to and finally to <head> <script type="text/javascript"> <!-- function popup(url ...