Google Maps API v3: Add Polylines inside a loop? - javascript

I'm in the process of migrating our Map application from V2 to V3 (3.2).
I had a loop that read LatLng and put them in a array to display as a Polyline on the map.
I then set the length of my array to 0 and then fill it again in the loop with other LatLng to display another Polyline... and so on (many times).
It was working fine in V2, but not in V3.
Since my code is complex, I tried to write the simpliest code possible to demonstrate my issue:
function setPolyline(points) {
var polyline = new google.maps.Polyline({
path: points,
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2
});
polyline.setMap(map);
}
var mapDiv = document.getElementById('map');
var mapCenter = new google.maps.LatLng(0,0);
var mapOptions = {
zoom: 2,
center: mapCenter,
backgroundColor: '#E1E1E1',
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapDiv, mapOptions);
var points=[];
points[0]=new google.maps.LatLng(-35, 71);
points[1]=new google.maps.LatLng(-36, 75);
points[2]=new google.maps.LatLng(-37, 91);
setPolyline(points);
points.length=0;
points[0]=new google.maps.LatLng(-31, 71);
points[1]=new google.maps.LatLng(-32, 75);
setPolyline(points);
What happens is that only the second Polyline is shown (and not the first one).
To make it works, I have to either use a different variable name (points1, points2, points3, ...) which I can't use because my code is normally in a loop or re-declare my variable each time in the loop instead of before it (var points=[] before each Polyline and remove the points.length=0 line).
Maybe I'm missing something about JavaScript, but I usually declare my variable outside the loop (before) once and use it inside the loop.
What am I doing wrong?
Can someone help?
Here's a simple Map I did to demonstrate my issue:
http://www.canamgroup.ws/GM.nsf/Map?OpenPage
(It's not in a loop, but the issue is the same. Only the last Polyline is displayed if I don't use a different variable name for my array or if I don't re-declare it each time)
Thanks!

In case it might help somebody, see this other discussion:
http://code.google.com/apis/maps/documentation/javascript/forum.html?place=topic%2Fgoogle-maps-js-api-v3%2FLp9tYYwkph4%2Fdiscussion

Related

Leaflet Multipolyline

i want to use the addLatLng function to add a new point to my multipolyline. I am able to use the function with a normal single polyline, but with for example two lines, i don't know how i can access the second ring to add the new point.
I have tried some of those...
var polyline = L.polyline([[], []], {color: generateRandomColor()}).addTo(map);
var point = {lat: lat, lng: long};
var arr = polyline.getLatLngs();
polyline[1].addLatLng(point); //nope
polyline.addLatLng(arr[1], point); //nope
polyline.addLatLng(point) //yes but adds to the first polyline
I also can't understand the hint from the docs -
addLatLng( latlng, <LatLng[]> latlngs?)
Adds a given point to the polyline. By default, adds to the first ring of the polyline in case of a multi-polyline, but can be overridden by passing a specific ring as a LatLng array (that you can earlier access with getLatLngs).
Can you please give me an example in javascript code?
Thank you so much!
You add the ring in the wrong order. Use following:
polyline.addLatLng(point, arr[1]); //yep

Polylines showing incorrectly

I have an array of Lat/Lng's that I would like to be able to display on a poly line.
Apologies if this is not very clear, please let me know HOW TO IMPROVE.
Here is an example of the array (Note the third object is the heading):
"Cot":[-37.582214,172.307343,null,-37.576828,172.321808,65.0,-37.155396,173.440231,65.0,-37.151962,173.45285,70.0,-37.148872,173.465286,70.0,-37.145985,173.477768,75.0,-37.138184,173.520584,75.0,-37.136169,173.532623,80.0,-37.054092,174.024567,80.0,-37.052032,174.03653,75.0,-37.043655,174.084564,75.0,-37.041733,174.096069,80.0,-37.007034,174.300613,80.0,-37.004932,174.312897,75.0,-36.99559,174.366943,75.0,-36.993576,174.378922,80.0,-36.989849,174.400497,80.0,-36.987946,174.411575,75.0,-36.981812,174.445007,75.0]
There are multiple aircraft(markers) on the map, when I use the code below it will read the first lat/lng of the array and if I click on another marker it will draw a line to another marker how ever I would like to be able to have a poly line behind each marker that shows when the user clicks on the marker and updates as the marker moves instead of it drawing a line to another marker start point (As seen in images below).
path.push(new google.maps.LatLng(p.Cot[0] , p.Cot[1]));
poly.setPath(path);
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(Map);
var path = new google.maps.MVCArray();
// every time the path is updated, automatically the map will update the polyline
Images to help explain whats going wrong:
https://ibb.co/n5n2Gc
https://ibb.co/jauShH

Add Polygon with array of points

I have a set of markers created around an area and I want to join them together to create a polygon (and shade it). My polygon code:
var polygon = new google.maps.Polygon({
paths: points,
strokeColor: '#f33f00',
fillColor: '#ff99aa',
fillOpacity: 0.2
});
polygon.setMap(map);
Where I have
var points = new Array();
points.push(new google.maps.LatLng(prev_dest.y, prev_dest.x));
Is the .push command no longer working in V3? Previously this worked:
map.addOverlay(new GPolygon(points, "#f33f00", 5, 1, "#ff99aa", 0.2));
Push is simply adding items to the array it has nothing to do with Google Maps API.
For a polygon to know its "closed" - make sure your first and last point in the array of points are the same - otherwise its not a valid polygon.
if its not simply add your fist point again to the array of points.

Convert zip code to latitude/longitude coordinates using Google Maps API?

I've been looking through the docs and all over the web for an example of this and I can't find an example of this use-case.
Given a zip code, I need a rough approximation of the user's location in the form of lat/long coordinates. All I have is the zip code, nothing else.
Can this be done using Google Maps API? If not, what other resources would you suggest looking at?
You can pass any text as the address key for the geocoder. If the geocoding is successsful, you should get an array of results.
From then on you can pick the first result or iterate over the array. Each of its elements should contain an address object, and postal code is one posible field on that obj.
Keep in mind that usps zipcodes are not points nor shapes. They are arrays of points, and the centroid of the polygon drawn by using those points as vertexes probably doesn't have any special meaning.
maybe you can do this by php with the following script:
function getLnt($zip){
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
$result1[]=$result['results'][0];
$result2[]=$result1[0]['geometry'];
$result3[]=$result2[0]['location'];
return $result3[0];
}
if you call this function by (* I filtered out the space between chars, it isn't necessary):
$coords = str_replace(' ','',$foo->zipcode);*
$val = getLnt($coords);
/* print latitude & longitude for example */
print $val['lat'];
print $val['lng'];
Then after that u can mix it with your google map script like:
function initialize(){
var myLatlng = new google.maps.LatLng(<?= $val['lat'] ?>,<?= $val['lng'] ?>);
var mapOptions = {
zoom: 14,
center: myLatlng,
disableDefaultUI: true,
scrollwheel: false,
}
var map = new google.maps.Map(document.getElementById('propMap'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'title of location',
icon: iconBase + 'google-marker.png'
});
}
Note: This worked fine for me, but maybe there are better ways to do this ;-)

Google Maps - Attaching InfoWindows to polygons in array

I've been banging my head against the wall all morning with this one. I an creating an array of polygons, and want to associate some data in each one that will show in an infoWindow. I can see all the polygons on the map. I add the listener, and it fires (the color change happens), but I don't get the infoWindow. Any help would be greatly appreaciated!
Cheers!
C...
tmppoly = new google.maps.Polygon({
map: map,
paths: polypath,
strokeColor: scolor,
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: fcolor,
fillOpacity: 0.5
});
addPolygonClick(tmppoly,mdata);
plot_polygons.push(tmppoly);
...
function addPolygonClick(poly,html) {
infowindow = new google.maps.InfoWindow(
{
content: html
});
google.maps.event.addListener(poly,'click', function(event) {
this.setOptions({fillColor: "#000000"});
infowindow.open(map);
});
}
I can provide some useful suggestions about your question.
Firstly, you should know the expression about the method 'infowindow.open(map, anchor?:MVCObject)'. As the google api v3 says: In the core API, the only anchor is the Marker class. Polygon class does not match the condition, however, we can achieve in another way.
var polygon = new google.maps.Polygon({
paths: PGpoints, //The PGpoints is the collection of points around this polygon.
map: map,
strokeColor: colory,
strokeOpacity: 0.6,
strokeWeight: 1,
fillColor: colory,
fillOpacity: 0.35
});
polygon.set("Info", idy); // Set some attributes for adding extra information into this polygon.
google.maps.event.addListener(polygon, 'click', function() {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent("Information : " + polygon.get("Info"));
// 'laty,lngy' is the location of one point in PGpoints, which can be chosen as you wish
infoWindow.setPosition(new google.maps.LatLng(laty,lngy));
infoWindow.open(map);
});
The code above has passed test, you can use it directly. Then, if you click one polygon, infoWindow would appear above the map.
There are a few problems that might be preventing this from working:
1:
You need a var in front of infowindow, to make it a local variable:
var infowindow = new google.maps.InfoWindow(...
As it is, you are replacing the infowindow variable every time you add a new click listener.
2:
You need to specify a position or anchor for the infowindow (see: http://code.google.com/apis/maps/documentation/javascript/reference.html#InfoWindowOptions).
The only valid anchor is a Marker, so you will probably want to specify the 'position' property. 'position' must be a valid google.maps.LatLng object. I suspect you will want to compute the center of your polygon to use as the position.
You also need to make sure map is a global variable, although it likely is looking at the rest of your code.
Please take a look at this https://developers.google.com/maps/documentation/javascript/examples/event-closure and combine it with the response above to assign a unique message for each polygon in your array of polygons.
I am also working in having multiple polygons in one layer with unique message for each polygon. I have not succeeded yet. With the response above, I got info window to show up, but I get the same message for all the polygons.
Once I solve my problem, I will post the solution.

Categories

Resources