Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting http.get data into local JSON array variable

I am very new to Angular and Nodejs and thought this would be a fun project to try. I am trying to get the the json data from the http.get in angular.js and put it into a variable cities so it can display on the google maps.

When I try to console.log(cities); it returns an object but console.log(cities.items) returns and undefined;

When i try to see the if i can JSON.stringify the data inside the $http.get it display the data below which is what i am trying to accomplish. Is there another way to get this data into the var cities so i can use it as shown below?

    {
      "city": "New York",
      "state": "NY",
      "desc": "Google NYC",
      "lat": 40.7418,
      "long": -74.0045
    }

Any help is greatly appreicated

angular.js

//Angular App Module and Controller
var sampleApp = angular.module('mapsApp', []);

   var cities = $http.get('/locations').success(function (data){
    $scope.items = data.items;
    })

    var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(41.5, -73),
        mapTypeId: google.maps.MapTypeId.TERRAIN
    }

    $scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);

    $scope.markers = [];

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

    var createMarker = function (info) {

        var marker = new google.maps.Marker({
            map: $scope.map,
            position: new google.maps.LatLng(info.lat, info.long),
            title: info.city
        });
        marker.content = '<div class="infoWindowContent">' + info.desc +          '</div>';

        google.maps.event.addListener(marker, 'click', function () {
            infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
            infoWindow.open($scope.map, marker);
        });
        $scope.markers.push(marker);
    }

    for (i = 0; i < cities.length; i++) {
        createMarker(cities[i]);
    }
    $scope.openInfoWindow = function (e, selectedMarker) {
        e.preventDefault();
        google.maps.event.trigger(selectedMarker, 'click');
    }
});

googleMaps.html

<!DOCTYPE html>
<html ng-app="mapsApp">
<head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
    <link rel="stylesheet" href="css/maps.css">
    <script            src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js">    </script>
    <script
            src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
    <script type="text/javascript" src="js/maps.js"></script>
</head>
<body>
<div ng-controller="MapCtrl">
    <div id="map"></div>
    <div id="repeat" ng-repeat="marker in markers | orderBy : 'title'">
        <a id="country_container" href="#" ng-click="openInfoWindow($event, marker)">
            <label id="names" >{{marker.title}}</label></a>
    </div>
    <ul>
        <li ng-repeat="item in items">
            {{item}}
        </li>
    </ul>
</div>
</body>
</html>

app.js

//Rest HTTP stuff
var express = require('express');
var bodyParser = require('body-parser');
var dbGoogle = require('./dbGoogle');
var app = express();

// configure body parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

var port = process.env.PORT || 8080; // set our port

// create our router
var router = express.Router();

// middleware to use for all requests
router.use(function (req, res, next) {
    // do logging
console.log('Incoming request..');
next();
});

// test route to make sure everything is working
router.get('/', function (req, res) {
res.json({message: 'Welcome!'});
});
router.route('/locations')

// get all the locations
.get(function (req, res) {
        dbGoogle.getGoogles(function (err, data) {
            if (data) {
                res.json({
                    status: '200',
                    items: data
               });
            } else {
               res.json(404, {status: err});
           }
        });
    })
// Register routes
app.use('', router);

//Serve static content files
app.use(express.static('public'));

// START THE SERVER
app.listen(port);
console.log('Running on port ' + port);

db.js

var mysql = require('mysql');
var app = require('./app.js');

var pool = mysql.createPool ({
    host: 'localhost',
    user: 'root',
    port: 3306,
    password: 'password',
    database: 'testdb'
});

module.exports.pool = pool;

pool.getConnection(function(err){
    if(!err) {
        console.log("Database is connected\n\n");
    } else {
        console.log(err);
    }
});

dbGoogle.js

var db = require('./db.js');

var getGoogles = function getGoogles(callback) {
    db.pool.getConnection(function (err, connection) {
        // Use the connection
        connection.query('SELECT * FROM locations', function(err, results){
            if (!err) {
                if (results != null) {
                    callback(null, results);
                } else {
                    callback(err, null);
                }
            } else {
                callback(err, null);
            }
            //release
            connection.release();
        });

    });
}

module.exports.getGoogles = getGoogles;
like image 214
user3464613 Avatar asked Dec 14 '15 04:12

user3464613


2 Answers

Try to create the markers asynchronous, something like

$http.get('/locations').success(function (data){
    angular.forEach(data.items, function(item) {
        createMarker(item);
    });
})
like image 84
omer-r Avatar answered Nov 03 '22 23:11

omer-r


because $http.get returns promise object.. so when you assign the $http.get to cities its not the data returned by the server its just the promise object.. what you have done right is in your success callback where you did $scope.items = data.items; this is the callback where you get the data from the server.. welcome to the world of Async

one solution could be to put all your code that uses cities.items inside success callback but it'll be a dirty code. But you get the idea..

like image 1
Minato Avatar answered Nov 03 '22 23:11

Minato