patternjavascriptMinor
Drawing multiple polygons in Google Maps in the same style
Viewed 0 times
samethegooglemapsstyledrawingmultiplepolygons
Problem
To multiple Polygon objects in Google maps, I have to set same strokeWeight, fillColor and fillOpacity attributes. Is there a way how to add these only once or do it in a better way?
var hospitalPath = new google.maps.Polygon({
path: hospitalPathCoords,
strokeWeight: 0,
fillColor: '#add78b',
fillOpacity: 0.8
});
hospitalPath.setMap(map);
var airportPath = new google.maps.Polygon({
path: airportPathCoords,
strokeWeight: 0,
fillColor: '#add78b',
fillOpacity: 0.8
});
airportPath.setMap(map);
var restaurantPath = new google.maps.Polygon({
path: restaurantPathCoords,
strokeWeight: 0,
fillColor: '#add78b',
fillOpacity: 0.8
});
restaurantPath.setMap(map);Solution
You have several options to reduce the code duplication here.
-
Put the common values into variables, and replace all hardcoded values with those new variables.
-
Create a prototype object of all the properties, and when you create a new polygon instance, copy the prototype instance and overwrite only the field you want to change (the
-
I saved my favorite to last. Create a helper function that takes a
Whichever way you choose, you will be able to change values in one place for all map instances, and thereby avoid much of the code duplication.
-
Put the common values into variables, and replace all hardcoded values with those new variables.
-
Create a prototype object of all the properties, and when you create a new polygon instance, copy the prototype instance and overwrite only the field you want to change (the
path in these examples).-
I saved my favorite to last. Create a helper function that takes a
path and returns a new polygon instance, configured with the common values, and the specified path.Whichever way you choose, you will be able to change values in one place for all map instances, and thereby avoid much of the code duplication.
Context
StackExchange Code Review Q#161039, answer score: 4
Revisions (0)
No revisions yet.