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.
Related
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.
So I have this code:
$.getJSON( "fetch-beacons.php", function( beacons ) {
beacons.forEach(function(beacon) {
if (beacon.uid != "<?php echo $uid ?>"){
var circle = new google.maps.Circle({
strokeColor: '#add8e6',
strokeOpacity: 0.8,
fillColor: '#add8e6',
fillOpacity: 0.35,
map: map,
center: new google.maps.LatLng(Number(beacon.lat), Number(beacon.lng)),
radius: Number(beacon.radius)
});
circle.addListener('click', function() {
post('claimcreds.php', {id: beacon.id, cid: <?php echo $uid ?>, uid: beacon.uid, lat: pos.lat, lng: pos.lng, claimattempt: "true"});
});
}
else {
var circle = new google.maps.Circle({
strokeColor: '#ffa500',
strokeOpacity: 0.8,
fillColor: '#ffa500',
fillOpacity: 0.35,
map: map,
center: new google.maps.LatLng(Number(beacon.lat), Number(beacon.lng)),
radius: Number(beacon.radius)
});
}
});
});
It's fetching details about some circles from a JSON document, and it works fine. The problem is, I want to check the circle position against another position (let's call it pos) every 10 seconds, to see whether pos is inside the circle.
As I understand it, the way to do this is google.maps.geometry.spherical.computeDistanceBetween(circle.center, pos); and then see if the radius is more or less than that, however I'm not sure how I'd do that every ten seconds, given that the circle variables aren't saved as they are looped through by the beacons.forEach statement.
Can anyone help? Sorry if what I'm asking isn't clear/if the code's a bit messy hehe :)
I think I would do something like this. Firstly define a global function like:
function checkDistance(circle) {
var distance = google.maps.geometry.spherical.computeDistanceBetween(circle.getCenter(), pos);
if (distance > x) {
alert('ok');
}
}
It takes one parameter, circle. I'm assuming pos is a global variable it can access.
Then inside your forEach loop, after your if-else statement (assuming you want to apply it to both kinds of circle), call that function on a 10.5 second interval. It uses the circle variable you've just created as a parameter you pass to the function:
setInterval(checkDistance, 10500, circle);
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/
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){}
});
Is there a way to bring a block's polygon (and its polylines) to the top layer?
I'm drawing polylines (to form polygons) for blocks in a city. Each block polygon is outlined with white polylines:
block = new google.maps.Polygon({
paths: blockCoordinates,
strokeColor: '#ffffff',
strokeOpacity: 1.0,
strokeWeight: 2,
fillColor: '#ff0000',
fillOpacity: shadeValue
}); }
When I hover over a block, I want the outline to turn black. I currently have this code:
google.maps.event.addListener(flightPath, 'mouseout', function (event) {
this.setOptions({
strokeColor: '#ffffff'
});
});
google.maps.event.addListener(flightPath, 'mouseover', function (event) {
this.setOptions({
strokeColor: '#000000'
});
});
However, it's not working on all the blocks.I think that is because (depending on the order of how the blocks are drawn), sometimes the polylines of other blocks are "above" the current block polylines.
If I set the white polylines to opacity of 0 (and black to an opacity of 1). It works fine but I, of course, don't get the pretty white lines between the blocks.
I had the same problem with several overlapping Polylines. The way I solved this is by initializing the Polyline with a zIndex. For you it should look something like:
block = new google.maps.Polygon({
paths: blockCoordinates,
strokeColor: '#ffffff',
strokeOpacity: 1.0,
strokeWeight: 2,
fillColor: '#ff0000',
fillOpacity: shadeValue,
zIndex: 1
}); }
Now you should able to change the zIndex of the Polylines using your mouseover and mouseout events like this:
google.maps.event.addListener(flightPath, 'mouseout', function (event) {
this.setOptions({
strokeColor: '#ffffff',
zIndex: 1
});
});
google.maps.event.addListener(flightPath, 'mouseover', function (event) {
this.setOptions({
strokeColor: '#000000',
zIndex: 2
});
});
The initialization isn't strictly necessary, but you could run into unexpected behavior if you don't.