We are using cartodb.js with Google map v3. We are trying to highlight the polygons on mouse-hover. Is there a way to highlight the polygon on Google map using cartodb layer?
1 Answer
One of the things you can do is request the geometry from cartoDB as in a geoJSON format as part of your SQL query:
SELECT *,ST_ASGEOJSON(the_geom) AS geometry FROM your_table
Google can take the geoJSON and convert it to polylines and polygons each time you mouse over a feature. Here's an example I've done with a polyline. You could do the same thing with a polygon, but use google.maps.Polygon() instead.
First create your shape (I created a global one so I could edit it easier).
var polylineHighlight = new google.maps.Polyline();
var polyOptions = {
strokeOpacity: 0.9,
strokeWeight: 13,
visible: false,
zIndex: 20
};
For more information on doing this with a Polygon, check out the Google Maps API (https://developers.google.com/maps/documentation/javascript/examples/polygon-simple)
Then this code would be used as part of your cartoDB featureover callback (via http://docs.cartodb.com/cartodb-platform/cartodb-js.html#create-a-visualization-from-scratch) :
.done(function(vis, layers) {
layers[1].on('featureOver', function(ev, pos, latlng, data) {
//Parse the geoJSON
var geometryJSON = $.parseJSON(data.geometry);
var pathCoordinates = new google.maps.MVCArray();
var temp = geometryJSON['coordinates'];
//Step through each coordinate pair
for (j = 0; j < temp.length; j++){
var latLongArr = geometryJSON['coordinates'][j];
for(i = 0; i < latLongArr.length; i++) {
var lon = latLongArr[i][0];
var lat = latLongArr[i][1];
//Place each coordinate is put into a LatLng and push that into an array of coordinates.
var latlng = new google.maps.LatLng(lat, lon);
pathCoordinates.insertAt(i,latlng);
}
}
// Change polyline location
var polyOptions = { path: pathCoordinates };
polylineHighlight.setOptions(polyOptions);
polylineHighlight.cartodb_id = data.cartodb_id;
}
}
Don't forget to make sure your cartoDB interactivity is turned on.