3
\$\begingroup\$

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);
\$\endgroup\$
4
\$\begingroup\$

You have several options to reduce the code duplication here.

  1. Put the common values into variables, and replace all hardcoded values with those new variables.

  2. 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).

  3. 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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.