interact with geojson layers independently in google maps api v3

允我心安 提交于 2019-11-30 01:07:54

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!