I am adding areas of interest in google maps using polygons and circles.
In each polygon and circle I'm adding an ID so I can get detailed information about that area if the user clicks on the polygon or circle.
There are cases that two areas overlap. By clicking the common area I'm able to get the ID for the object that is "above" but I have no way to get the ID of the object that lies "below". An example is given below.
Is there a way to get the IDs of overlapping objects?
The code that creates a polygon and a circle is given below.
function drawpolygonExersice(res, ExerciseID){
var points = new Array();
var ptn;
for (var j=0;j<res.length/2;j++)
{ptn = new google.maps.LatLng(res[2*j],res[2*j+1]);
points.push(ptn);}
var polygonExercise = new google.maps.Polygon({
path: points,
geodesic: true,
strokeColor: 'red',
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: "red",
fillOpacity: 0.20,
ID: ExerciseID, //look up ID
map: map
});
google.maps.event.addListener(polygonExercise, 'click', function(event) {
alert(this.ID);
});
exerciseAreas.push(polygonExercise);
}
function drawcircleExersice(res, ExerciseID) {
var circleExercise = new google.maps.Circle ({
center: new google.maps.LatLng(res[0],res[1]),
radius: res[2] * 1852, //Nautical miles to meters
geodesic: true,
strokeColor: 'red',
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor:'red',
fillOpacity: 0.20,
ID: ExerciseID, //look up ID
map: map
});
google.maps.event.addListener(circleExercise, 'click', function(event) {
alert(this.ID);
});
exerciseAreas.push(circleExercise);
}
The only way I see is to iterate over all shapes and calculate(via geometry-library) if a shape contains the clicked latLng. It shouldn't be a problem with the expected amount of shapes.
For a circle use .computeDistanceBetween(clickedLatLng,circle.getCenter()), when the result is <=circle.getRadius() , the click has been on the circle.
For a polygon use .containsLocation(clickedLatLng,polygon), when it returns true the click has been on the polygon.
Demo: http://jsfiddle.net/doktormolle/qotg0o2x/
Related
I have some code that loops through an array of airline routes and airports placing markers at each airport and drawing polylines between them. The code works and is fine when I have 400 routes. When I expand it to the full ~3500ish routes it grinds to a halt for nearly a minute rendering. Is there any way I can speed this up?
map.fitBounds(bounds);
var flightPath;
var flightPlanCoordinates;
$.each(routes, function(key, route) {
flightPlanCoordinates = [];
flightPlanCoordinates.push( markers[route.origincode].position );
flightPlanCoordinates.push( markers[route.destinationcode].position );
flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#004494',
strokeOpacity: 0.2,
strokeWeight: 1
});
flightPath.setMap(map); //commenting this line speeds things back up
google.maps.event.addListener(flightPath, 'mouseover', function (event) {
this.setOptions({
strokeOpacity: 1,
strokeWeight: 2
});
});
google.maps.event.addListener(flightPath, 'mouseout', function (event) {
this.setOptions({
strokeOpacity: 0.2,
strokeWeight: 1
});
});
});
I suggest you to request and decode the direction json data in background before the MapsActivity start. And your can also storage the decode LatLng in SharedPreferencd(eg: 1->(1.12,1.32), 2->(1.32, 2.52)) making it a flow-data instead of storage all date in an array which will cost you many resource and reduce the runnig-speed. At last, take LatLng data from SharedPreferenced and pain them.
When I initiate the map I have this listener:
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
console.log('value of e');
console.log(e);
polyArray.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
}
setMapClickEvent(e.overlay, e.type);
setSelection(e.overlay);
});
Immediatly after this declaration I loop through the current rectangles that should be automatically drawn on the map. This is the code:
_.each($scope.currentRactangles, function(arr) {
new google.maps.Rectangle({
strokeColor: '#002288',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#333322',
fillOpacity: 0.35,
map: map,
editable: true,
bounds: new google.maps.LatLngBounds(
new google.maps.LatLng(arr.upper_lat, arr.upper_lng),
new google.maps.LatLng(arr.lower_lat, arr.lower_lng)
)
});
});
Now, when map is loaded, the existing rectangles (fetched from database) are drawn on the map.
However, the listener never gets triggered.
If I manually draw a rectangle, the I can see in the console "value of e" and the event itself.
My question is: is it possible to trigger the listener when drawing rectangles programmatically?
All this because when I store the rectangles in database, I will store stuff inside the array "polyArray". Which only contains rectangles created manually.
Ok, solution was about storing in the array the newly created rectangles. Basically this snippet:
var tmprect = new google.maps.Rectangle({
strokeColor: '#002288',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#333322',
fillOpacity: 0.35,
map: map,
editable: true,
bounds: new google.maps.LatLngBounds(
new google.maps.LatLng(arr.upper_lat, arr.upper_lng),
new google.maps.LatLng(arr.lower_lat, arr.lower_lng)
)
});
var newrect = {};
newrect.type = 'rectangle';
newrect.overlay = tmprect;
polyArray.push(newrect);
Even if the rectangles from database didn't generated an event they are now inside the same array that will also contain the rectangles manually drawn. That was enough for me as I only needed a way to store rectangles both from user and the automatically generated.
I am using the Maps API v3 and added a GeoJSON file to create a circle (based on google.maps.Symbol objects) around each entry in the GeoJSON-file -- which works quite fine by using the setStyle-functionality:
map.data.addGeoJson('url_to_GeoJSON');
..
map.data.setStyle(function(feature) {
return /** #type {google.maps.Data.StyleOptions} */({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 5,
fillColor: '#f00',
fillOpacity: 0.5,
strokeWeight: 0
}
});
});
Now I would need to draw a circle with a static radius in meters around each point, like it is provided by the regular google.maps.CircleOptions with its 'radius'.
Is there any possibility to use the very comfortable data layer 'addGeoJson'- and 'setStyle'-features in combination with a geographically correct radius in meters around each point?
I would be very happy to avoid setting up each marker manually "the old way" by iterating through the whole GeoJSON-file with
new google.maps.Circle({radius: 20000});
Any help is greatly appreciated! Thanks in advance!
After adding the code of Dr. Molle, there seems to be an issue while using multiple google.maps.Data-Objects, that should be shown/hide by checking/unchecking a checkbox within the website. This is my actual code, which already shows the data layer with drawn circles, but does not hide the circles of the specific data layer when unchecking a checkbox:
var map;
var dataset1 = new google.maps.Data();
var dataset2 = new google.maps.Data();
var dataset3 = new google.maps.Data();
function initialize() {
// Create a new map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 6,
center: {lat: 50.678240, lng: 9.437256},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
checkDataset();
}
function checkDataset() {
if (document.getElementById('chkDataset1').checked) {
// Define styles for dataPlug9 and apply to map-object.
dataset1.setStyle(function(feature) {
var geo = feature.getGeometry();
// Check for a point feature.
if(geo.getType().toLowerCase()==='point'){
//create a circle
feature.circle = new google.maps.Circle({
map: map,
center: geo.get(),
radius: 200000,
fillColor: '#FF0000',
fillOpacity: 0.05,
strokeColor: '#FF0000',
strokeOpacity: 0.4,
strokeWeight: 1
});
//trigger the dblclick-event of map.data on a dblclick on the circle
google.maps.event.addListener(feature.circle, 'dblclick',function(e){
e.stop();
google.maps.event.trigger(this.getMap().data,'dblclick', {feature:feature})
});
// Hide the marker-icon.
return {visible:false};
}});
// Remove feature on dblclick.
google.maps.event.addListener(dataset1,'dblclick',function(f){
this.remove(f.feature);
});
// Remove circle too when feature will be removed.
google.maps.event.addListener(dataset1,'removefeature',function(f){
try{f.feature.circle.setMap(null);}catch(e){}
});
dataset1.loadGeoJson('data/plug1.json');
dataset1.setMap(map);
} else {
dataset1.removefeature();
// This doesn't work either ..
dataset1.setMap(null);
}
}
I also added the above routine of function checkDataset() for the other 2 datasets (dataset2 and dataset3) and changed 'dataset1' to 'dataset2 / dataset3'.
You don't need to iterate "manually", setStyle already iterates over the features.
You may use it to execute additional code(e.g. create a google.maps.Circle):
map.data.setStyle(function(feature) {
var geo= feature.getGeometry();
//when it's a point
if(geo.getType().toLowerCase()==='point'){
//create a circle
feature.circle=new google.maps.Circle({map:map,
center: geo.get(),
radius: 20000,
fillColor: '#f00',
fillOpacity: 0.5,
strokeWeight: 0});
//and hide the marker when you want to
return {visible:false};
}});
Edit:
related to the comment:
The circles will be saved as a circle-property of the features(note: this property is not a property in the meaning of geoJSON, so it may not be accessed via getProperty).
You may add a listener for the removefeature-event and remove the circle there, so the circle will be removed when you remove the feature.
Sample code that will remove a feature(including the circle) on dblclick:
map.data.setStyle(function(feature) {
var geo= feature.getGeometry();
//when it's a point
if(geo.getType().toLowerCase()==='point'){
//create a circle
feature.circle=new google.maps.Circle({map:map,
center:geo.get(),
radius:200000,
fillColor: '#f00',
fillOpacity: 0.5,
strokeWeight: 0});
//trigger the dblclick-event of map.data on a dblclick on the circle
google.maps.event.addListener(feature.circle, 'dblclick',function(e){
e.stop();
google.maps.event.trigger(this.getMap().data,'dblclick',{feature:feature})
});
//and hide the marker
return {visible:false};
}});
//remove the feature on dblclick
google.maps.event.addListener(map.data,'dblclick',function(f){
this.remove(f.feature);
});
//remove the circle too when the feature will be removed
google.maps.event.addListener(map.data,'removefeature',function(f){
try{f.feature.circle.setMap(null);}catch(e){}
});
I want to paint any country with any color and cover it in google maps. I find a way to draw polygon by coordinates:
var mypolygon;
var polyCoords = [
new google.maps.LatLng(40.96985437850034, 45.871337890625),
new google.maps.LatLng(40.936664923030236, 49.00244140625),
new google.maps.LatLng(39.76454453848205, 47.50830078125)
];
mypolygon = new google.maps.Polygon({
paths: polyCoords,
strokeColor: "#FF0000",
strokeOpacity: 1,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 1
});
mypolygon.setMap(map);
It works, but it is not possible (or its very difficult) to find all border coordinates of country. Asume that possible. It will be approximately, not exactly.
Is there any way to cover a country with any color by it's name? For example, for our country - Azerbaijan: "az".
I created some google.maps.Marker and did bind google.maps.Circle to it (see below):
But when I open street view, I see only Marker:
Does anybody know how to show Circle in street view mode?
Sounds like I can't do that.
Maybe someone knows how to show 2D/3D objects into Google-Street-View.
Any suggestion?
Thanks,
This is snippets of code:
var circle = {
strokeColor: "#006DFC",
strokeOpacity: 0.4,
strokeWeight: 2,
fillColor: "#006DFC",
fillOpacity: 0.15,
map: mapA,
center: selectedMarker.getPosition(),
radius: 50 // in meters
};
var cityCircle = new google.maps.Circle(circle);
cityCircle.bindTo('center', selectedMarker, 'position');
You could use a Symbol instead of a google.maps.Circle to draw the circle, it will be visible on the panorama.
Getting a 3D-effect would be more complicated, but it should be possible to modify the path of the symbol on the pov_changed-event of the panorama.