interact with geojson layers independently in google maps api v3

后端 未结 1 654
悲哀的现实
悲哀的现实 2020-12-24 08:47

I would like to load two geojson layers to my map and be able to style them independently with different rules. I can display both my geojson files with the below code, but

相关标签:
1条回答
  • 2020-12-24 09:28

    So I just had to do something similar and needed to add 2 geojson files and style them differently. What you want to do is initialize the map and then add 2 different layers. Basically set the styling for both. Below is my code with notes. I actually used this function Angular in a service and returned a promise.

    Set up your map options

    var mapOptions = {
                zoom: 4,
                scrollwheel: false,
                center: new google.maps.LatLng(40.00, -98),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
    

    Set your map to a variable.

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

    Initialize 2 variable that will take layers. I did state and county.

    var countyLayer = new google.maps.Data();
    var stateLayer = new google.maps.Data();
    

    Then load the GeoJson files for each layer.

    countyLayer.loadGeoJson('counties.json');
    stateLayer.loadGeoJson('states.json');
    

    After that set the style for each layer.

    stateLayer.setStyle({
      strokeColor: 'red',
      strokeWeight: 5
     });
    
    countyLayer.setStyle({
      strokeColor: 'black',
      strokeWeight: 1
    });
    

    The last step is to set the layer to the map.

    countyLayer.setMap(map);
    stateLayer.setMap(map);
    

    After this I returned a promise but you could just return the map object. Does this make sense / help answer your question?

    Also, within each layer setStyle() function you can add dynamic styling through functions. Like add a function to fillColor that would change the color based on data in the GeoJson file.

    0 讨论(0)
提交回复
热议问题