Center a boundary of polygons in Google Maps - javascript

I am trying to find a better way to center my google map.
I've already written code to add in Markers to Outline and area squarely of which is being store in an array: Coords[i], in-which when returning to the map after save, it centers the map window based on the "first marker" lat/lng coordinates Coords[0].
I am trying to figure out a better way to center the map where there is adequate space around my outline area.
I've try doing it on Dragend, which works somewhat:
google.maps.event.addListener(this.map, 'dragend', function(mapEvent) {
var lat = mapEvent.getCenter() .lat(),
lng = mapEvent.getCenter() .lng(),
console.log(lat + " " + lng + " " + this);
});
But it keeps throwing an error saying:
"Unable to get property 'getCenter' of undefined or null reference"
Can someone tell me what I am doing wrong OR tell be a better way to achieve what I'm trying to do?
As, another option
It would be nice if possible if I can keep the first marker [0] the centering marker as it is already, But don't allow it to outline... just the markers 1 + and on .... But I don't know how to modify my code to do that.
Just looking for a solution that works.
My complete Code is here:
http://pastiebin.com/embed/593d6d809e2f0

You can use a LatLngBounds object. Loop through your Polygons if you have more than one and extend your bounds object with each path coordinates.
LatLngBounds
You can then make your map fit the bounds object so it will zoom and center accordingly by using map.fitBounds().
fitBounds
If you use multi-paths Polygon, make sure you use getPaths method instead of getPath as in the code below.
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var polygon = new google.maps.Polygon({
editable: true,
strokeOpacity: 0,
strokeWeight: 0,
fillColor: '#00FF00',
fillOpacity: .6,
paths: [
new google.maps.LatLng(39, 4),
new google.maps.LatLng(34, 24),
new google.maps.LatLng(43, 24),
new google.maps.LatLng(39, 4)],
map: map
});
// Create the bounds object
var bounds = new google.maps.LatLngBounds();
// Get paths from polygon and set event listeners for each path separately
polygon.getPath().forEach(function (path, index) {
bounds.extend(path);
});
// Fit Polygon path bounds
map.fitBounds(bounds);
}
initialize();
#map-canvas {
height: 200px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>

Ok I just figured out a way!
I simply grabbed the lat/lng coordinates of the center of the polygon drawn and centered my whole map with that.
var bounds = new google.maps.LatLngBounds();
var i;
//Get Center of Saved Coordinates of the drawn polygons
for (var i = 0; i < values["coords"].length; i++) {
bounds.extend(values["coords"][i]);
}
var movemaplat = bounds.getCenter().lat();
var movemaplng= bounds.getCenter().lng();
console.log("MY MAP CENTER " + movemaplat + ", " + movemaplng);
Thanks to #Daniel Vassallo's answer here: How to get the center of a polygon in google maps v3?

Related

Getting the latitude and longitude of the point in between (by percentage) two points on Google Maps JS API?

Here is the code I have so far:
function initialize() {
var mapOptions = {
center: { lat: 21.9072222, lng: -47.715},
zoom: 3
};
var map = new google.maps.Map(document.getElementById('derby-to-lima'),
mapOptions);
var line = new google.maps.Polyline({
path: [new google.maps.LatLng(53.9834124, -1.5863153), new google.maps.LatLng(-12.0553442, -77.0451853)],
strokeColor: "#008CBA",
geodesic: true,
strokeOpacity: 0.5,
strokeWeight: 5,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I want to draw another line on top of the existing one that stops at the point in between the two points, which can be changed by percentage. It's kind of hard to explain, but imagine the first point is the start, and the last is the end. You are given how far a runner currently is by the percentage of the way through they are. Now show how far they are (assuming they ran in a straight line).
Thanks, I've been stuck on this for a while.
As suggested by #Dr.Molle load the geometry library and use the method interpolate.
var startPoint = new google.maps.LatLng(53.9834124, -1.5863153);
var endPoint = new google.maps.LatLng(-12.0553442, -77.0451853);
var percentage = 0.5;
var middlePoint = new google.maps.geometry.spherical.interpolate(startPoint, endPoint, percentage);
FIDDLE

Google map load more than 1000 markers browser not responding

I am new to Google maps, I am plotting the gps data onto a Google map, it works fine up to 500 points. If the data exceeds more than 500 it slows down is there any alternate way to plot markers onto a map.
I am just marking the gps data in Google map on certain time period.
Later I need to plot hundreds of thousands of gps data in Google map,below method slows down and exit the firefox or chrome (it times out).
How to plot more data on google map and also it should be fast
My javascript code, sale data will be of json data:
function show_map_all_data(sale_data)
{
init_map();
var count_actual=sale_data.length;
var locations=[];
for (var i=0;i<count_actual;i++)
{
var temp=[]
temp.push(sale_data[i]['GPS_latitude'],sale_data[i]['GPS_longitude'])
locations.push(temp);
}
//console.log(locations);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
icon: {
path: google.maps.SymbolPath.CIRCLE,
strokeColor: '#8e2014',
scale: 4,
strokeOpacity: 1.0,
strokeWeight: 10,
fillColor: '#8e2014',
animation: google.maps.Animation.DROP,
},
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0] + "," + locations[i][1]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
You'll likely need to look into markerclustering in order to speed up your page load times (and avoid time out). Multiple markers rendered on the client side is probably the downfall of many mapping applications performance wise. It is difficult to benchmark, fix and in some cases even establish there is an issue (due to browser implementation differences, hardware available to the client, mobile devices, the list goes on).
The simplest way to begin to address this issue is to use a marker clustering solution. The basic idea is to group geographically similar locations into a group with the number of points displayed. As the user zooms into the map these groups expand to reveal individual markers beneath.
Perhaps the simplest to implement is the markerclusterer library. A basic implementation would be as follows (after library imports, and not reflective of your code, this is just the simplest example I could come up with):
<script type="text/javascript">
function initialize() {
var center = new google.maps.LatLng(37.4419, -122.1419);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markers = [];
for (var i = 0; i < 100; i++) {
var location = yourData.location[i];
var latLng = new google.maps.LatLng(location.latitude,
location.longitude);
var marker = new google.maps.Marker({
position: latLng
});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
The markers instead of being added directly to the map are added to an array. This array is then passed to the library which handles complex calculation for you and attached to the map.
Not only do these implementations massively increase client side performance but they also in many cases lead to a simpler and less cluttered UI and easier digestion of data on larger scales.
Other implementations are available from Google.
Edit to answer comment
If you look here: http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/docs/reference.html and look for a property called maxZoom you can set a zoom level in the clusterer options object after which the clustering will be turned off to allow all markers to be plotted.

can't draw a polyline on google maps v3, but can draw the points of it as markers (I am using OpenStreetMap layer)

the following code is used to draw a polyline on Google Maps using V3 API, but sometimes is draws the polyline and most of times doesn't despite there are point (as I can show the points on the map as markers) but no polyline appears
update 2 : I am using openstreetmap layer over Google maps. does that cause the problem when drawing the polyilne ?
w variable contains data as string , for example :
w= 35.1212,55.2333\n36.32366,56.3333
Real data sample for w : [this code can draw markers for the following points but can't draw a polyline ]
34.440501,31.515222
34.441933,31.514346
34.44247,31.514013
34.442603,31.51394
34.443607,31.513423
34.4445,31.512926
34.444762,31.512772
34.445186,31.512523
34.445257,31.512481
34.445311,31.512449
34.445614,31.512264
34.446244,31.511867
34.446939,31.511429
34.447351,31.511193
34.448081,31.512174
34.448241,31.512357
34.448576,31.512741
34.449147,31.513185
34.4499,31.513723
34.450894,31.514401
34.451925,31.515362
34.452905,31.516176
34.454194,31.517266
34.455337,31.518236
34.456215,31.51898
34.456987,31.519646
34.457583,31.520166
34.458298,31.520772
34.458989,31.52139
34.459659,31.521959
34.460476,31.522653
34.461192,31.523228
34.461869,31.523788
34.46256,31.524376
34.463302,31.525015
34.464062,31.525668
34.464433,31.525986
34.464737,31.526246
34.465247,31.526683
34.465498,31.526907
34.466666,31.52792
34.46722,31.528404
34.467327,31.528495
34.468014,31.529081
34.468379,31.52939
34.469296,31.530177
34.469771,31.530583
34.470152,31.53091
34.470951,31.531597
34.471617,31.532172
34.472388,31.532838
34.472664,31.533076
34.47295,31.533397
34.473422,31.533653
34.474028,31.534065
34.474844,31.534629
34.475725,31.535253
34.476083,31.535517
34.476697,31.535947
34.477105,31.536209
34.477627,31.536477
34.478,31.536742
34.478398,31.536989
34.478935,31.537325
34.480044,31.537975
34.480985,31.538529
34.481362,31.53878
34.481416,31.538819
34.482407,31.539419
34.482682,31.539109
34.483132,31.538603
34.483341,31.538368
34.483917,31.537753
34.484202,31.537449
34.484288,31.537357
34.484944,31.536587
34.485118,31.536383
34.485205,31.536304
34.485648,31.535903
34.485984,31.535598
34.486246,31.535381
34.486445,31.535291
34.486533,31.535254
34.486607,31.535282
34.486706,31.535354
34.486869,31.535526
34.487012,31.535692
34.487212,31.535923
34.487273,31.536006
34.487767,31.53571
34.488336,31.535395
34.48883,31.535148
34.489078,31.535032
34.489354,31.534901
34.48955,31.534788
34.489756,31.535011
34.489831,31.535097
34.490268,31.534748
34.49065,31.534473
34.490857,31.53436
34.491044,31.534319
34.491352,31.534248
34.491458,31.534237
34.491548,31.534304
34.491879,31.534209
34.492227,31.534203
34.492457,31.534214
34.492042,31.533636
34.492162,31.533542
note : I have reversed lng and lat when creating a point for some purpose
where a is array that has the points to represent as a polyine
code
var mypolyline = new google.maps.Polyline({
strokeColor: "#FF0000",
strokeOpacity: .6,
strokeWeight: 3,
clickable: true
});
// var bounds2 = new google.maps.LatLngBounds();
var a=w.split("\n");
for(var i=0;i<a.length;i++)
{
var zz=a[i].split(",");
var lat=zz[0];
var lng=zz[1];
var path = [];
var path = mypolyline.getPath();
var point = new google.maps.LatLng(parseFloat(lng),parseFloat(lat));
createMarker(i,name,point,icon[1],2);
// alert(path.length);
path.push(point);
mypolyline.setPath(path);
mypolyline.setMap(map);
}
CreateMarker() function
function createMarker(id,name,point,icon,type) {
// var marker = new google.maps.Marker(point, customIcons[type]);
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon
});
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow = new google.maps.InfoWindow({ content: name });
infowindow.open(map, marker);
map.panTo(point);
});
return marker;
}
So you create an array, then you ignore that and recreate it as an MVCArray using the getPath() function. Get rid of the first line (this isn't the cause of the problems though).
var path = [];
var path = mypolyline.getPath();
Just a thought - is the path a required attribute when you first create the polyline?
It seems to me that you initially create the mypolyline without any path. So when you then do this on the first iteration, it's not going to work, because all you're passing to .setPath() is one point, but I assume a path can only work when there's at least 2 points.
path.push(point);
mypolyline.setPath(path);
Update: I think the thing to do would be to just start out with an empty array, loop over your coordinates adding them into the array. Then after the loop, create the polyline, rather than trying to update it each time you iterate over the loop. For instance:
var a=w.split("\n");
var path = [];
for(var i=0;i<a.length;i++)
{
var zz=a[i].split(",");
var lat=zz[0];
var lng=zz[1];
var point = new google.maps.LatLng(parseFloat(lng),parseFloat(lat));
createMarker(i,name,point,icon[1],2);
path.push(point);
}
var mypolyline = new google.maps.Polyline({
path: path,
map: map,
strokeColor: "#FF0000",
strokeOpacity: .6,
strokeWeight: 3,
clickable: true
});

Google Maps v3 API Extend Bounds. Javascript How-To?

function initialize(){
// Creating a map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(53.0123601276819, -2.44519164333635),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var m = [];
function addMarker(title, lat, lng) {
m[m.length] = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: title,
clickable: true,
icon: 'http://domain.com/MVC/images/full.png'
});
}
addMarker('Home', 53.0682143712504, -2.52150736731894);
addMarker('Away', 53.0123601276819, -2.44519164333635);
addMarker('Away', 59.0123601276819, -2.44519164333635);
// Create a LatLngBounds object
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < m.length; i++) {
// Insert code to add marker to map here
// Extend the LatLngBound object
bounds.extend(m[i]);
}
alert(m[0]);
map.fitBounds(bounds);
document.write(getBounds());
}
The above is my code.
My intentions are to develop a map which shows numerous markers and pans the zoom such that all the markers fit on my screen.
I am new to JS.
My understanding is that
var m = [];
creates an empty array.
Then everytime i call addMarker() the details get added to this array m
At the top I set a default zoom and center point.
I then add various markers.
I then loop through each key in the m array and extend the bounds using the data from this.
It is then my understanding that map.fitBounds(bounds); should redefine the zoom/center as applicable to fit all the markers.
It does not.
All my markers show, but the zoom/center is not auto adjusting as such, and I have no idea why.
Any advice would be greatly appreciated.
Thanks
You need to pass a LatLng object to the bounds.extend function.
Here is the code :
....
bounds.extend(new google.maps.LatLng(lat, lng));
....
Here is a clarification of the above answer which is correct except it's missing a parenthesis and a little brief.
//make an empty bounds variable
var bounds = new google.maps.LatLngBounds();
//do your map stuff here
//special note: make sure your lat and lng are floats or googleMaps will error
var lat = 38.103;
var lng = -121.572;
bounds.extend(new google.maps.LatLng(lat, lng));
//adjust the viewport of the map
//special note: this only needs to be done once, don't put it in a loop
map.fitBounds(bounds);

How do I add and remove Polygons on Google Maps v3?

I'm trying to show and remove polygons onto a Google Map, using v3 of the API. In my JavaScript, I've already got an MVCArray of some custom Lat-Longs.
I'm trying to figure out how to add these polygons and then, based upon some other JavaScript event or user action, such as a click on a polygon (that has been rendered), that polygon will be removed.
Are any code examples available? I'm struggling to find some; most of them usually go to some v2 code.
In the API docs, there are a couple of simple examples of adding a polygon to a map. Here's the initialize() function from the simple Bermuda Triangle example with the addition of adding an event listener to remove the polygon when clicked.
function initialize() {
var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
var myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var bermudaTriangle;
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var triangleCoords = [
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.75737),
new google.maps.LatLng(25.774252, -80.190262)
];
// Construct the polygon
bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
// add an event listener
google.maps.event.addListener(bermudaTriangle, 'click', function() {
this.setMap(null);
});
}
I'm not sure if this answer applies to javascript, but definitely applies to java.
If you have a reference to the polygon object you want to remove, then simply call the remove() method of that polygon. Refer to the documentation linked below.
https://developers.google.com/android/reference/com/google/android/gms/maps/model/Polygon.html#remove()

Categories