8

次のダイレクト コードはhttp://jsfiddle.net/M6RPn/26/から のものです。多くの緯度と経度を持つ json フィードを取得したい..Angular で $resource または $http を使用して json を簡単に取得できますが、どうすればこのディレクティブにフィードして、マップ上にマップしますか?

module.directive('sap', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {
            var map = L.map(attrs.id, {
                center: [40, -86],
                zoom: 10
            });
            //create a CloudMade tile layer and add it to the map
            L.tileLayer('http://{s}.tile.cloudmade.com/57cbb6ca8cac418dbb1a402586df4528/997/256/{z}/{x}/{y}.png', {
                maxZoom: 18
            }).addTo(map);

            //add markers dynamically
            var points = [{lat: 40, lng: -86},{lat: 40.1, lng: -86.2}];
            for (var p in points) {
                L.marker([points[p].lat, points[p].lng]).addTo(map);
            }
        }
    };
});
4

4 に答える 4

13

リーフレットやあなたが何をしようとしているのかについてはよくわかりませんが、コントローラーからディレクティブに座標を渡したいと思いますか?

それを行うには実際には多くの方法があります...その最良の方法は、スコープを活用することです。

コントローラーからディレクティブにデータを渡す 1 つの方法を次に示します。

module.directive('sap', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {
            var map = L.map(attrs.id, {
                center: [40, -86],
                zoom: 10
            });
            //create a CloudMade tile layer and add it to the map
            L.tileLayer('http://{s}.tile.cloudmade.com/57cbb6ca8cac418dbb1a402586df4528/997/256/{z}/{x}/{y}.png', {
                maxZoom: 18
            }).addTo(map);

            //add markers dynamically
            var points = [{lat: 40, lng: -86},{lat: 40.1, lng: -86.2}];
            updatePoints(points);

            function updatePoints(pts) {
               for (var p in pts) {
                  L.marker([pts[p].lat, pts[p].lng]).addTo(map);
               }
            }

            //add a watch on the scope to update your points.
            // whatever scope property that is passed into
            // the poinsource="" attribute will now update the points
            scope.$watch(attr.pointsource, function(value) {
               updatePoints(value);
            });
        }
    };
});

これがマークアップです。ここでは、リンク関数が $watch を設定するために探している pointsource 属性を追加しています。

<div ng-app="leafletMap">
    <div ng-controller="MapCtrl">
        <sap id="map" pointsource="pointsFromController"></sap>
    </div>
</div>

次に、コントローラーに、更新できるプロパティがあります。

function MapCtrl($scope, $http) {
   //here's the property you can just update.
   $scope.pointsFromController = [{lat: 40, lng: -86},{lat: 40.1, lng: -86.2}];

   //here's some contrived controller method to demo updating the property.
   $scope.getPointsFromSomewhere = function() {
     $http.get('/Get/Points/From/Somewhere').success(function(somepoints) {
         $scope.pointsFromController = somepoints;
     });
   }
}
于 2012-10-19T04:04:01.767 に答える
5

最近、 AngularJSLeafletを使用してアプリを作成しました。JSONファイルからの位置データを含め、これまでに説明した内容と非常によく似ています。私の解決策はbleshに似ています。

これが基本的なプロセスです。

自分<map>のページの1つに要素があります。<map>次に、要素をリーフレットマップに置き換えるディレクティブがあります。JSONデータをファクトリにロードするため、セットアップは少し異なりますが、ユースケースに合わせて調整しました(エラーがある場合はお詫びします)。ディレクティブ内で、JSONファイルをロードしてから、各場所をループします(互換性のある方法でJSONファイルを設定する必要があります)。次に、各緯度/経度にマーカーを表示します。

HTML

<map id="map" style="width:100%; height:100%; position:absolute;"></map>

指令

app.directive('map', function() {
return {
    restrict: 'E',
    replace: true,
    template: '<div></div>',
    link: function(scope, element, attrs) {

        var popup = L.popup();
        var southWest = new L.LatLng(40.60092,-74.173508);
        var northEast = new L.LatLng(40.874843,-73.825035);            
        var bounds = new L.LatLngBounds(southWest, northEast);
        L.Icon.Default.imagePath = './img';

        var map = L.map('map', {
            center: new L.LatLng(40.73547,-73.987856),
            zoom: 12,
            maxBounds: bounds,
            maxZoom: 18,
            minZoom: 12
        });



        // create the tile layer with correct attribution
        var tilesURL='http://tile.stamen.com/terrain/{z}/{x}/{y}.png';
        var tilesAttrib='Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.';
        var tiles = new L.TileLayer(tilesURL, {
            attribution: tilesAttrib, 
            opacity: 0.7,
            detectRetina: true,
            unloadInvisibleTiles: true,
            updateWhenIdle: true,
            reuseTiles: true
        });
        tiles.addTo(map);

        // Read in the Location/Events file 
        $http.get('locations.json').success(function(data) {
            // Loop through the 'locations' and place markers on the map
            angular.forEach(data.locations, function(location, key){

                var marker = L.marker([location.latitude, location.longitude]).addTo(map);

            });
        });
    }
};

サンプルJSONファイル

{"locations": [     
{   
    "latitude":40.740234, 
    "longitude":-73.995715
    }, 
{   
    "latitude":40.74277, 
    "longitude":-73.986654
    },
{   
    "latitude":40.724592, 
    "longitude":-73.999679
    }
]} 
于 2013-03-14T06:42:59.170 に答える
1

あなたのコントローラーであなたが得たと仮定すると

$scope.points = // here goes your retrieved data from json

ディレクティブ テンプレートは次のとおりです。

<sap id="nice-map" points="points"/>

次に、ディレクティブ定義内で「=」記号を使用して、ディレクティブ スコープと親スコープの間の双方向バインディングをセットアップできます。

module.directive('sap', function() {
return {
    restrict: 'E',
    replace: true,
    scope:{
      points:"=points"
    },
    link: function(scope, element, attrs) {
        var map = L.map(attrs.id, {
            center: [40, -86],
            zoom: 10
        });
        L.tileLayer('http://{s}.tile.cloudmade.com/57cbb6ca8cac418dbb1a402586df4528/997/256/{z}/{x}/{y}.png', {
            maxZoom: 18
        }).addTo(map);

        for (var p in points) {
            L.marker([p.lat, p.lng]).addTo(map);
        }
    }
};
});

また、マーカーをマップに直接追加する代わりに、最初にマーカーを L.featureGroup に追加してから、その L.featureGroup をマップに追加することをお勧めします。これは、clearLayers() メソッドがあるためです。マーカーを更新しています。

grupo = L.featureGroup();
grupo.addTo(map);

for (var p in points) {
    L.marker([p.lat, p.lng]).addTo(grupo);
}


// remove all markers
grupo.clearLayers();

これがお役に立てば幸いです、乾杯

于 2013-05-30T04:37:07.737 に答える
1

angularJs のディレクティブと mvc は異なるテクノロジです。通常、ディレクティブはページの読み込み時に実行されます。ディレクティブは、html および xml を操作するためのものです。JSON を取得したら、mvc フレームワークを使用して作業を行うのが最善です。

ページがレンダリングされた後、ディレクティブを適用するには、多くの場合、$scope.$apply() または $compile を実行してページに変更を登録する必要があります。

いずれにせよ、サービスをディレクティブに入れる最善の方法は、依存性注入フレームワークを使用することです。

scope:true または scope:{} がディレクティブにないことに気付きました。これは、ディレクティブが親コントローラーでどれだけうまく機能するかに大きな影響を与えます。

app.directive('mapThingy',['mapSvc',function(mapSvc){
  //directive code here.

}]);

app.service('mapSvc',['$http',function($http){
 //svc work here.
}])

ディレクティブは、camelCase マッチングによって適用されます。IE の問題があるため、 or の使用は避けたいと思います。代替案は

<div map-thingy=""></div>
于 2013-03-27T21:37:07.473 に答える