multiple polygons, InfoWindow, setMap - javascript

well, I've spent a while on this, and I've stumbled my way through and got this far with the help of many tutorials and examples.
I need to create multiple polygons each with a separate InfoWindow. Think I've got that but having trouble with setMap. This is how far I've got:
Getting a type error
object #<object> has no method 'setMap'
How can I fix this error?
<script>
var map;
var infoWindow;
function initialize() {
var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
var mapOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
// Let's start with an empty object:
var countries = {
};
// Now let's add a county polygon:
countries['UK'] = new google.maps.Polygon({
paths: [
new google.maps.LatLng(59.677361, -2.469846),
new google.maps.LatLng(59.299717, -6.314917),
new google.maps.LatLng(57.877247, -9.314917),
new google.maps.LatLng(54.428078, -11.638861),
new google.maps.LatLng(51.784554, -11.702241),
new google.maps.LatLng(50.185848, -10.054354),
new google.maps.LatLng(49.405380, -7.012100),
new google.maps.LatLng(49.090675, -3.272664),
new google.maps.LatLng(48.775970, -1.709283),
new google.maps.LatLng(49.757851, -2.089565),
new google.maps.LatLng(50.714554, 1.037195),
new google.maps.LatLng(51.482437, 2.304801),
new google.maps.LatLng(53.433609, 3.276632),
new google.maps.LatLng(55.863132, 3.445646)
// ...
],
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.3
});
// Next county:
countries['FR'] = new google.maps.Polygon({
paths: [
// This is not real data:
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.757370),
new google.maps.LatLng(25.774252, -80.190262)
// ...
],
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.3
});
// And so on...
countries.setMap(map)
;
// Add a listener for the click event
google.maps.event.addListener(UK, 'click', showInfoUK);
google.maps.event.addListener(FR, 'click', showInfoFR);
infowindow = new google.maps.InfoWindow();
}
function showInfoUK(event) {
var contentString = "<b>UK</b><br />";
contentString += "UK, Channel Islands, Ireland";
// Replace our Info Window's content and position
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
function showInfoFR(event) {
var contentString = "<b>FR</b><br />";
contentString += "France, N,W";
// Replace our Info Window's content and position
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
</script>

Javascript doesn't have references to keys like for example php, so countries['UK'] is not possible to set. You have to use numeric keys. So syntax should be something like this:
countries[0] = new google.maps.Polygon({ ... });
countries[1] = new google.maps.Polygon({ ... });
I made your example working:
http://jsfiddle.net/AcCzT/15/
Can be finetuned. It's not perfect. It's just a quick fix.
You can go on from there

Javascript arrays do not have a .setMap() method. google.maps.Polygon() objects do. Additionally, there are no associative arrays in javascript, such as countries['UK']
This might work:
countries['UK'].setMap(map);
but it wouldn't be correct.

There are two issues in your code:
What Marcelo said, to add the polygon to the map, use: countries["UK"].setMap(map);
To add the click listener, you need to reference the polygon: google.maps.event.addListener(countries["UK"], 'click', showInfoUK);
working example

use ajax easier, more plain.
for example,
downloadUrl("url", function(data) {
for (var i = 0; i < polygons.length; i++) {
........
var decodedPath = ........
polygon.setMap(map);
........
}
});

Related

Google Maps time trace route

How about everyone.
I have a question on how to start using google maps.
I explain:
I'm doing a system where the position (latitude and longitude) of businesses enter and I have customers who also income the position (latitude and longitude) this is in a database, then suppose that there are four restauranes and I want automatically when I discharged my system assign a customer already restored more fences position.
I show an image as an explanation.
Thanks and regards.
Im not quite sure I understand your question but here's a code I used to trace route for a set of Latitude and Longitude values:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA8lPDzcCN2E1icji4hSjmHgH-uFieMcX8&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 18,
center: new google.maps.LatLng(13.035307999999999,77.5688322),
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var flightPlanCoordinates = [
// set of (lat,long) values
new google.maps.LatLng(13.03545513,77.56844698),
new google.maps.LatLng(13.035312,77.56885567),
new google.maps.LatLng(13.03541774,77.56790266),
new google.maps.LatLng(13.0347358,77.56854116),
new google.maps.LatLng(13.0350667,77.56892307),
new google.maps.LatLng(13.03534067,77.56951356),
new google.maps.LatLng(13.03557602,77.56923249),
new google.maps.LatLng(13.03559478,77.56825478),
new google.maps.LatLng(13.03558727,77.5672599),
new google.maps.LatLng(13.03542425,77.5681003),
new google.maps.LatLng(13.03530649,77.5689072)
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>

GoogleMaps addlistener zip popup?

Alright, this has been a problem for me for 3 days, javascript closures are just not my strong suit.
I have a google map which I've applied an overlay with a series of clickable polygons. I want a specific function to run depending on the polygon clicked, which I have working. The problem is I can't figure out how to work the listener so that a function that displays an infowindow with that polygon's zip code in it. Here's the code:
for (x = 0; x < 50 && coordsObject.length > x; x++) { //Only draw 50 polygons at a time
...
//create zipcoords array
clickablePolygons.push(new google.maps.Polygon({
paths: zipCoords
, strokeColor: "#000"
, strokeOpacity: 1
, strokeWeight: 1
, fillColor: convertRatingToHex(rating)
, fillOpacity: 0.45
}));
infoWindow.push(
new google.maps.InfoWindow({
content: '<div id="gcontent">' + zip.toString() + '</div>'
})
);
//problem child
var theFunction = function(arguments, infowindow, map) {
var marker = new google.maps.Marker({
position: arguments[0].latLng
});
infowindow.open(map, marker);
};
google.maps.event.addListener(clickablePolygons[clickablePolygons.length - 1], 'click', function() {
theFunction(arguments, infoWindow[x], map); //:(
});
clickablePolygons[clickablePolygons.length - 1].setMap(map);
}
What am I doing wrong with the closure?
in your addListener call you have function() and not function(arguments). I would also create a variable pointing to the infoWindow outside the call to addlistener. The assumption is that the click event will pass in the arguments that you are expecting. It may need to be function(e,arguments).
var win = infoWindow[x];
google.maps.event.addListener(clickablePolygons[clickablePolygons.length - 1], 'click', function(arguments) {
theFunction(arguments, win, map);
});
Looks like variable scoping problem, give it a try
(function(x){
google.maps.event.addListener(clickablePolygons[clickablePolygons.length - 1], 'click', function(arg) {
theFunction(arg, infoWindow[x], map);
});
})(x);
You do not need multiple instances of an InfoWindow. Just use the methods to set the content and position when needed.
I do not understand why you are adding a marker, is that a requirement? If you just want an InfoWindow to show when the polygon is clicked you can use the MouseEvent object passed from the click event to get the current position of the click.
Here is an example: http://jsfiddle.net/bryan_weaver/akLBM/
code in the link:
var map;
var infoWindow;
var clickablePolygons = [];
function createPolygon(path, stateName) {
var poly = new google.maps.Polygon({
paths: path,
strokeColor: "#000",
strokeOpacity: 1,
strokeWeight: 1,
fillColor: "#330000",
fillOpacity: 0.45
});
//add the polygon to the array, to use later if needed.
clickablePolygons.push(poly);
//attach a click event, the first argument of the listener is the event
//you can get the position of the mouse cursor where the map
//was clicked through this.
google.maps.event.addListener(poly, "click", function (event) {
//call the setContent method and set the content for the info window
infoWindow.setContent("This state is: " + stateName);
//set the anchor of the info window, in this case
//I am using the mouse position at
//the time of the click
infoWindow.setPosition(event.latLng);
//open the info window, passing the map in which to attach it to.
infoWindow.open(map);
});
//add the polygon to the map
poly.setMap(map);
}
function initialize() {
var myLatLng =
new google.maps.LatLng(39.983994270935625, -111.02783203125);
var mapOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//polygon coords for Utah
var utah = [
new google.maps.LatLng(41.983994270935625, -111.02783203125),
new google.maps.LatLng(42.00032514831621, -114.01611328125),
new google.maps.LatLng(36.96744946416931, -114.01611328125),
new google.maps.LatLng(37.00255267215955, -109.0283203125),
new google.maps.LatLng(40.97989806962013, -109.0283203125),
new google.maps.LatLng(41.0130657870063, -111.02783203125)];
//polygon coords for Colorado
var colorado = [
new google.maps.LatLng(40.96330795307351, -109.05029296875),
new google.maps.LatLng(36.96744946416931, -109.0283203125),
new google.maps.LatLng(37.02009820136811, -101.9970703125),
new google.maps.LatLng(40.97989806962013, -102.06298828125)];
map = new google.maps.Map($('#map')[0], mapOptions);
//create a single info window for use in the application
infoWindow = new google.maps.InfoWindow();
//add the polygon and infowindow content to the map.
createPolygon(utah, "Utah");
createPolygon(colorado, "Colorado");
}
google.maps.event.addDomListener(window, 'load', initialize);

Using 2 methods to display markers and polylines on a Google map

I am trying to combine two separate methods to display both markers and polylines on one map. Is it possible? and if so how would I do this. Or conversely how would I add polylines to my markers sample.
From http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/
Without my actual code I appreciate this is a probably a wasted post.. but I am having trouble adding my code..
Perhaps that should have been my first question..
This script will add markers and draw a polyline between them:
<script>
var poly;
var map;
function initialize() {
var chicago = new google.maps.LatLng(41.879535, -87.624333);
var mapOptions = {
zoom: 7,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
// Add a listener for the click event
google.maps.event.addListener(map, 'click', addLatLng);
}
/**
* Handles click events on a map, and adds a new point to the Polyline.
* #param {MouseEvent} mouseEvent
*/
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
}
</script>
Excellent Documentation available here:
https://developers.google.com/maps/documentation/javascript/reference
https://google-developers.appspot.com/maps/documentation/javascript/examples/polyline-complex
It is certainly possible to display markers and polylines on the same map:
Here is an example that displays both markers and independent polylines.
Here is an example that uses the third party geoxml3 KML parser to create them from a KML file (or using KmlLayer).

Google Maps v3 - Can't get a polygon and/or rectangle to display on map

I've been working on a .NET geocoding application that at the end displays a Google Map (using the v3 API) of an address or place. The map has a marker in the centre representing the point that is geocoded. This all works. I then wanted to display a rectangle/polygon shape overlay on the map that represents the bounds surrounding the point that was geocoded (this reflects the accuracy of the geocoding, with larger bounds representing less accuracy). (I get the co-ordinates of these bounds back from the API query).
However, I just cannot get a polygon or rectange to display on the map and it's driving me crazy! I've followed the instructions in the documentation for polygons but no joy. I've tried google.maps.Polygon and google.maps.Rectangle, but with no luck for either. I've also tried different lat/lngs for the bounds but it made no difference. Nothing ever shows. I must be making some fundamental mistake, but can't see any trees in these woods!
The basic code (which is generated from C#) I have looks like this:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
if (window.attachEvent) {window.attachEvent('onload', initMap);}
else if (window.addEventListener) {window.addEventListener('load', initMap, false);}
else {document.addEventListener('load', initMap, false);}
function initMap() {
var latlng = new google.maps.LatLng(51.5001524,-0.1262362);
var myOptions = { zoom: 15, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker = new google.maps.Marker({
position: latlng, map: map, title:'Westminster, London, UK'
});
var boundCoords = [
new google.maps.LatLng(51.3493528),
new google.maps.LatLng(-0.378358),
new google.maps.LatLng(51.7040647),
new google.maps.LatLng(0.1502295),
];
var poly = new google.maps.Polygon({
paths: boundCoords, strokeColor: '#FF0000', strokeOpacity: 0.8,
strokeWeight: 3, fillColor: '#FF0000', fillOpacity: 0.35
});
poly.setMap(map);
console.log(poly);
}
</script>
<div id="map_canvas" style="width:640px; height:480px"></div>
There is a JSFiddle version available here you can play with.
new google.maps.LatLng(51.3493528),
You need x,y coords, for example
new google.maps.LatLng(32.321384, -64.75737),
OR
you need two markers, example:
var latLngBounds = new google.maps.LatLngBounds(
marker1.getPosition(),
marker2.getPosition()
);
rectangle.setBounds(latLngBounds);

Encapsulate Google Map V.3 event to listen object methods

I want to encapsulate google map polygon(google.maps.Polygon) and map (google.maps.Map) into a javascript object and handle some event for both polygon and map. Here is some code
function Landmark(map, polygon) {
this.map = map;
this.polygon = polygon;
// Add a listener for the click event
google.maps.event.addListener(this.map, 'click', this.addPoint);
google.maps.event.addListener(this.polygon, 'click', this.addPoint);
addPoint = function (event) {
alert("xxx");
}
}
I called the function using :
var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
var myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
polygonInTest = new google.maps.Polygon({
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});
polygonInTest.setMap(map);
var landmark = new Landmark(map, polygonInTest);
But when I trigger the event, by clicking the map, I got this error from firebug :
f.e is undefined
[Break On This Error] function de(a,b){var c,d=a.__e3_||{};i...n"+b]=c,c=new ce(a,b,c,3));return c};
Can anyone point me where have I done wrong and give some suggestions? Any comment or help is appreciated.
Thanks in advance.
My best guess is that when you are creating an event listener
google.maps.event.addListener(this.map, 'click', this.addPoint);
your handler is not yet defined (i.e. you define addPoint later), so at the time of addListener() call this.addPoint is undefined. And GMaps messes up later when the time comes for the handler to be called.
At least that's how I realized I had a problem at this point by looking at your code :)

Categories