yagajs / leaflet-ng2

Angular.io integration of Leaflet
https://leaflet-ng2.yagajs.org
ISC License
66 stars 26 forks source link

Center the map with the geojson's center. Also the bounds. #416

Closed jmateosmovisat closed 6 years ago

jmateosmovisat commented 6 years ago

When I draw a geojson, I'd like the map set automatic values depends of the geojosn.

In Leaflet it's done like this

jsonLayer = L.geoJson(data, {
                    style: {color: "#999", weight: 2, fillColor: "#00ad79", fillOpacity: .6},
                    onEachFeature: function (feature, layer) {
                        layer.bindPopup("<strong>" + feature.properties['DISTRICT'])
                    }
})
jsonLayer.addTo(map);
map.fitBounds(jsonLayer.getBounds());

But I have a component with

<yaga-map [lat]="info.latitude" [lng]="info.longitude" [zoom]="info.zoom">
    <yaga-zoom-control></yaga-zoom-control>
    <yaga-tile-layer [(url)]="info.tileLayerUrl"></yaga-tile-layer>
    <yaga-geojson *ngIf="info.geojson" [data]="info.geojson">
        <yaga-tooltip>Resultado</yaga-tooltip>
        <yaga-popup>Resultado</yaga-popup>
    </yaga-geojson>
</yaga-map>

the info.geojson is loaded by a service.

How can I set autocenter and auto bounds?

Thank you.

Congratulatios for your work

atd-schubert commented 6 years ago

I think the easiest way at the moment is to create a method in your app component applies this on the map. Something similar to these lines, but I haven't test them...

Your app component:

export class AppComponent implements AfterViewInit {
    @ViewChild(MapComponent) private mapComponent: MapComponent;
    @ViewChild("geojson",  {read: GeoJSONDirective}) private geojsonDirective: GeoJSONDirective;
    public fitBounds(): void {
        this.mapComponent.fitBounds(this.geojsonDirective.getBounds());
    }
}

Your app component's view:

<yaga-map [lat]="info.latitude" [lng]="info.longitude" [zoom]="info.zoom">
    <yaga-zoom-control></yaga-zoom-control>
    <yaga-tile-layer [(url)]="info.tileLayerUrl"></yaga-tile-layer>
    <yaga-geojson #geojson *ngIf="info.geojson" [data]="info.geojson" (dataChange)="fitBounds()">
        <yaga-tooltip>Resultado</yaga-tooltip>
        <yaga-popup>Resultado</yaga-popup>
    </yaga-geojson>
</yaga-map>

A more elegant way would be adding app component methods to the [lat], [lng] and [zoom] attributes, but this depends on your business-logic.

<yaga-map [lat]="calculateLat()" [lng]="calculateLng()" [zoom]="calculateZoom()">
  <!-- ... -->
</yaga-map>

A build-in possibility for that is not available in leaflet-ng2.

jmateosmovisat commented 6 years ago

Thanks for the quick reply.