使用Angularjs同步Leafletjs地图数据

时间:2015-08-03 16:04:54

标签: javascript json angularjs leaflet

我正在尝试创建一个应用程序,它从json文件中获取纬度和经度坐标(以及其他属性)并将它们应用到我的地图,以及过滤器和搜索选项。我一直在关注本教程:http://zevross.com/blog/2014/05/27/synchronize-leaflet-map-data-with-angularjs/ 我无法弄清楚我的json文件是否格式不正确,或者我是不是在我的javascript中迭代文件。感谢您的帮助。

controllers.js

'use strict';
myApp.controller('DemoController', ["$scope", "$http", '$q', '$filter',
function($scope, $http, $q, $filter) {

    $scope.search = {
        customer: '',
        year: ''
    }

    $scope.tableClick = function(dat){
         $scope.search.customer = dat.customer
    }

       // function countryClick(country, event) {
       //      console.log(country);
       //  }

    $scope.orderByField = 'year';

    $scope.$on("leafletDirectiveMap.geojsonMouseover", function(ev,      
    leafletEvent) {
        customerMouseover(leafletEvent);
    });

   $scope.$on("leafletDirectiveMap.geojsonClick", function(ev,    
   featureSelected, leafletEvent) {
            $scope.search.customer=featureSelected.properties.customer
        });

   $scope.clearSelections = function(){
    $scope.search.customer = ''
    $scope.search.year = ''
   }

    $scope.$watchCollection("search",
        function(newValue, oldValue) {

            if (newValue === oldValue) {
                return;
            }
            var data = angular.copy($scope.acct_year);

            var justGroup = _.filter(data.features, function(x) {
                if (newValue.year == '' || newValue.year == undefined) {

                    if (!newValue.customer) {
                        return true
                    } else {
                        return $filter('filter')([x.properties.customer],   
newValue.customer).length > 0
                    }
                } else {
                    if (!newValue.customer) {
                        return x.properties.year == newValue.year
                    } else {
                        return x.properties.year == newValue.year & $filter('filter')([x.properties.customer], newValue.customer).length > 0
                    }
                }

            })

            data.features = justGroup
            $scope.geojson = {
                data: data,
                style: style,
                resetStyleOnMouseout: true

            }

        }
    );

    angular.extend($scope, {
        center: {
            lat: 40.8471,
            lng: 14.0625,
            zoom: 2
        },
        scrollWheelZoom: false,
        legend: {
            colors: ['#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f'],
            labels: ['2010', '2011', '2012', '2013', '2014', '2015']
        }
            });


    var opac = 0.8
    var circlecolors = {
        '2010': {
            color: '#7fc97f',
            opacity: opac
        },
        '2011': {
            color: '#beaed4',
            opacity: opac
        },
        '2012': {
            color: '#fdc086',
            opacity: opac
        },
        '2013': {
            color: '#ffff99',
            opacity: opac
        },
        '2014': {
            color: '#386cb0',
            opacity: opac
        },
        '2015': {
            color: '#f0027f',
            opacity: opac
        }

    }

        function getColorFootball(d) {

            return circlecolors[d.year] || {
                color: 'grey',
                opacity: 0
            }

        }



        function style(feature) {
            var vals = getColorFootball($scope.footballObject[feature.properties.ISO3])
            var rads = getRadiusFootball($scope.footballObject[feature.properties.ISO3])
            return {
                fillColor: vals.color,
                radius: rads,
                color: "#000",
                weight: 1,
                opacity: 1,
                fillOpacity: vals.opacity
            };
        }


        function getRadiusFootball(d) {


            if (d) {
                d = d['year']
                return Math.sqrt(1500 / d)
            } else {
                return 0
            }
        }


  $scope.acct_year= [];
   $http.get('acct_year_small.json').success(function(data, status) {
        var tempAcct_Json = {};

        for (var i = 0; i < data.length; i++) {
            var customer = data[i];
            tempAcct_Json[customer['CUSTOMER']] = customer;


        //then set on scope
        $scope.footballObject = tempAcct_Json;
        $scope.acct_year = data;
    }
    });



    // http://thematicmapping.org/downloads/world_borders.php
    // qgis to do centroids, move US, save as geojson
    $scope.acct_yeargeo = {};
    $http.get("world.geojson").success(function(data, status) {
        //data.features = data.sort(propSort(["PARK_NAME"]));
        var featuresLim = []
        var minrank = 0
        for (var i = 0; i < data.features.length; i++) {

            var amatch = _.where($scope.acct_year, {
                "alpha-3": data.features[i].properties['ISO3']

            })

            if (amatch.length > 0) {

                var feat = data.features[i]
                var currank = amatch[0]['year']


                var curgroup = amatch[0]['year']
                var curcountry = amatch[0]['customer']
                feat.properties['year'] = currank
                feat.properties['year'] = curgroup
                feat.properties['customer'] = curcountry

                featuresLim.push(feat)


            } //end if


        } //end loop through features
        featuresLim.sort(propSort("year"));
        //featuresLim.sort(sortBy)

        data.features = featuresLim


        $scope.acct_yeargeo = data
        angular.extend($scope, {
            geojson: {
                data: data,
                style: style,
                resetStyleOnMouseout: true
            }
        }); //end extend
    }); //end get features



    function countryMouseover(leafletEvent) {
        var layer = leafletEvent.target;
        layer.setStyle({
            weight: 2,
            color: '#666',
            fillColor: 'white'
        });
        //layer.bringToFront();
    }


    function propSort(props) {
        return function sort(a, b) {
            var p;
            a = a.properties;
            b = b.properties;

            p = props;
            if (a[p] < b[p]) return -1;
            if (a[p] > b[p]) return 1;
        };
    }




}
]);

//mapoptions
myApp.controller("GoogleMapsController", ["$scope",
function($scope) {
    angular.extend($scope, {
        world: {
            lat: 39.809860,
            lng: -98.555183,
            zoom: 4
        },
        scrollwheel: false,
        layers: {
            baselayers: {
                googleTerrain: {
                    name: 'Google Terrain',
                    layerType: 'TERRAIN',
                    type: 'google'
                }


            }
        },
        defaults: {
            scrollwheel: false
        }
        });
    }
    ]);

test2.html

<!DOCTYPE html>
<html lang="en" ng-app="myApp">

<head>
<meta charset="utf-8" />
<title>Map</title>
<link href="../css/bootstrap.min.css" rel="stylesheet" />
<link href="../css/leaflet.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css"   
href="http://cloud.github.com/downloads/lafeber/world-flags- 
sprite/flags32.css" />
<script src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"> 
</script>
<script 
src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-
min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" 
rel="stylesheet">
<link rel="stylesheet" href="../css/app.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.js"></script>

</head>

<body ng-controller="DemoController">


<div class="container">
    <div class="row">
        <h1>Map</h1>




    </div>
    <div class="row">
        <div ng-controller='GoogleMapsController'>
            <!-- <leaflet center="center" events="events" legend="legend"  
    geojson="geojson" width='100%' height='600'></leaflet> -->

            <leaflet center="world" events="events" legend="legend"   
    width='100%' height='400' layers='layers' geojson="geojson"></leaflet>


        </div>




        <div class="info country f32">
            <div ng-show="geojson.selected" class="flag" ng- 
            class="geojson.selected.properties.ISO2|lowercase"></div>
            <span class='countryselected' ng-cloak>{{ 
          geojson.selected.properties.NAME ?
          geojson.selected.properties.NAME + ' &#8212; Years ' +   
          footballObject[geojson.selected.properties.ISO3].year : 'Select   
          customer on map'}}</span>
        </div>


        <!--     <div class="info box">Map center: [ lat: {{ center.lat |  
       number:4 }}, lng: {{ center.lng | number:4 }} ]</div> -->


        <div class="col-md-10 col-md-offset-1">
            <div class="row well filtering">
                <form class="form-horizontal" role="form">
                    <div class="form-group">
                        <label for="search" class="col-sm-6 control- 
                         label">Filter by Customer</label>
                        <input ng-model="search.country">
                    </div>
                    <div class="form-group">
                        <label class="col-sm-6 control-label">Filter by  
                        Year</label>
                        <select class="selectpicker" ng-model='search.Group'  
 ng-options="city.Group as city.Group for city in acct_year | unique:'year'  
 | orderBy:'year'" fix>
 <option value="" selected="selected">-- All Years --</option>
                        </select>
    </div>
     <div class="form-group">
            <button type="button" class="btn btn-grey col-sm-2 col-sm-  
              offset-5" ng-click='clearSelections()'>Clear  
 Selections</button>
                    </div>

                </form>
            </div>

            <div class="row">
                <table ng-cloak class='table table-striped full'>
                    <thead>
                        <tr class="foot">
                            <th><a href="" ng-click="orderByField =  
      'customer'; reverse=!reverse">Customer</a>
                            </th>
                            <th><a href="" ng-click="orderByField = 
      'cust_code'; reverse=!reverse">Customer Code</a>
                            </th>
                            <th><a href="" ng-click="orderByField = 'grand 
       total'; reverse=!reverse">Grand Total</a>
                            </th>
                            <th><a href="" ng-click="orderByField = 'year'; 
       reverse=!reverse">Year</a>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="foot in acct_year | 
                       orderBy:orderByField:reverse | filter:search" ng-  
                            click="tableClick(foot)">
                            <td class='country'>{{foot.customer}}</td>
                            <td>{{foot.cust_code}}</td>
                            <td>{{foot.grand_total}}</td>
                            <td>{{foot.year}}</td>

                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
<hr>
        <footer>

</footer>
</div>
</body>

<script>
</script>

<script src="../js/angular.min.js"></script>
<script src="../js/angular-route.js"></script>
<script src="../js/angular-leaflet-directive.js"></script>
<script src="../js/app.js"></script>
<script src="../js/controllers.js"></script>
<script src="../js/directives.js"></script>
<script src="../js/filters.js"></script>
<script src="../js/Google.js"></script>
</body>

acct_year_small.json(只是一个测试文件,实际文件有更多数据)

features = 
[
  {
   "type": "Feature",
   "geometry": {
   "type": "Point",
   "coordinates":  [ -102.852,30.877528 ]
  },
   "properties": {
   "CUSTOMER":"Bridgestone Americas Tire Operations",
   "CUST_CODE":20,
   "GRAND TOTAL":"$11,311.82",
   "YEAR":2010
    }
  },
{
"type": "Feature",
"geometry": {
   "type": "Point",
   "coordinates":  [ -76.41533,39.337798 ]
},
"properties": {
"CUSTOMER":"D & M Equipment",
"CUST_CODE":47,
"GRAND TOTAL":"$4,500.00",
"YEAR":2010
 }
}
];

1 个答案:

答案 0 :(得分:0)

如果您的JSON文件正确,则需要更改

tempAcct_Json[customer['CUSTOMER']] = customer; 

tempAcct_Json[customer.properties['CUSTOMER']] = customer;