how to display tile layers in google earth api? - google-maps-api-3

I am creating an interactive map for a non profit association "Friends of Knox Mountain Park" but I am getting trouble with the Google Earth view.
This is the project: http://www.virtualbc.ca/knoxmountain/
and this is the code associated to google map's code:
google.load('earth', '1');
var map;
var googleEarth;
var gmarkers = [];
var iconShadow = new google.maps.MarkerImage('icons/shadow.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(46, 42),
new google.maps.Point(0,0),
new google.maps.Point(13, 42));
var sites = [
['1',49.905305,-119.491191, 37, '<img src="images/parking.jpg" />','parking'],
['2',49.905842,-119.481927, 36, '<img src="images/viewpoint.jpg" />','viewpoint'],
['3',49.907366,-119.490439, 35, '<img src="images/shelter.jpg" />','shelter'],
['4',49.907878,-119.491058, 34, '<img src="images/viewpoint.jpg" />','viewpoint'],
['5',49.908405,-119.491083, 33, '<img src="images/parking.jpg" />','parking'],
['6',49.910402,-119.492423, 32, '<img src="images/viewpoint.jpg" />','viewpoint'],
['7',49.911380,-119.480236, 31, '<img src="images/shelter.jpg" />','shelter'],
['9',49.911389,-119.480571, 30, '<img src="images/playground.jpg" />','playground'],
['a',49.911417,-119.485104, 29, '<img src="images/shelter.jpg" />','shelter'],
['b',49.911578,-119.479905, 28, '<img src="images/parking.jpg" />','parking'],
['8',49.911656,-119.480227, 27, '<img src="images/picnic.jpg" />','picnic'],
['c',49.91174271,-119.48507050, 26, '<img src="images/apex_point_high.jpg" />','icon'],
['d',49.911916,-119.485581, 25, '<img src="images/viewpoint.jpg" />','viewpoint'],
['e',49.912234,-119.485175, 24, '<img src="images/viewpoint.jpg" />','viewpoint'],
['f',49.912662,-119.485008, 23, '<img src="images/viewpoint.jpg" />','viewpoint'],
['g',49.91286999,-119.48413424, 22, '<img src="images/apex_point_low.jpg" />','icon'],
['h',49.913207,-119.482843, 21, '<img src="images/parking.jpg" />','parking'],
['i',49.914174,-119.472531, 20, '<img src="images/viewpoint.jpg" />','viewpoint'],
['j',49.914445,-119.482013, 19, '<img src="images/information.jpg" />','information'],
['k',49.914687,-119.482042, 18, '<img src="images/washroom.jpg" />','washroom'],
['l',49.914747,-119.482432, 17, '<img src="images/shelter.jpg" />','shelter'],
['m',49.914814,-119.483070, 16, '<img src="images/viewpoint.jpg" />','viewpoint'],
['n',49.915162,-119.482393, 15, '<img src="images/viewpoint.jpg" />','viewpoint'],
['o',49.916277,-119.481530, 14, '<img src="images/viewpoint.jpg" />','viewpoint'],
['p2',49.919028,-119.479564, 13, '<img src="images/viewpoint.jpg" />','viewpoint'],
['p',49.919065,-119.478622, 12, '<img src="images/viewpoint.jpg" />','viewpoint'],
['q',49.91971281,-119.47954356, 11, '<img src="images/gordon_trail_1.jpg" />','icon'],
['r',49.919778,-119.479044, 10, '<img src="images/viewpoint.jpg" />','viewpoint'],
['s',49.920243,-119.480118, 9, '<img src="images/viewpoint.jpg" />','viewpoint'],
['t',49.922075,-119.481165, 8, '<img src="images/viewpoint.jpg" />','viewpoint'],
['u',49.924514,-119.478223, 7, '<img src="images/swim.jpg" />','swimming'],
['v',49.924599,-119.477396, 6, '<img src="images/washroom.jpg" />','washroom'],
['w',49.924867,-119.477636, 5, '<img src="images/picnic.jpg" />','picnic'],
['x',49.925053,-119.477334, 4, '<img src="images/picnic.jpg" />','picnic'],
['y',49.925211,-119.476506, 3, '<img src="images/picnic.jpg" />','picnic'],
['z',49.925446,-119.476789, 2, '<img src="images/swim.jpg" />','swimming'],
['z2',49.92555541,-119.47710250, 1, '<img src="images/tomb_bay.jpg" />','icon']
];
var infowindow = null;
var overlay;
// Used to make Google Map quard coords to MapCruncher/BingMaps quard coords
function TileToQuadKey ( x, y, zoom)
{
var quad = "";
for (var i = zoom; i > 0; i--)
{
var mask = 1 << (i - 1);
var cell = 0;
if ((x & mask) != 0)
cell++;
if ((y & mask) != 0)
cell += 2;
quad += cell;
}
return quad;
}
function init() {
var centerMap = new google.maps.LatLng(49.909671,-119.482241);
var myOptions = {
zoom: 10,
center: centerMap,
mapTypeId: google.maps.MapTypeId.SATELLITE
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Create the tile layers
// ASTER Tile Layer
myASTEROptions = {
getTileUrl : function (a,b) {
return "http://www.virtualbc.ca/knoxmountain/map/" + TileToQuadKey(a.x,a.y,b) + ".png";
},
isPng: true,
opacity: 1.0,
tileSize: new google.maps.Size(256,256),
name: "ASTER",
minZoom:13,
maxZoom:20
}
ASTERMapType = new google.maps.ImageMapType( myASTEROptions );
map.overlayMapTypes.insertAt(0, ASTERMapType);
// Aerial Tile Layer
myAerialOptions = {
getTileUrl : function (a,b) {
return "http://www.virtualbc.ca/knoxmountain/map/" + TileToQuadKey(a.x,a.y,b) + ".png";
},
isPng: true,
opacity: 1.0,
tileSize: new google.maps.Size(256,256),
name: "Aerial",
minZoom:15,
maxZoom:21
}
AerialMapType = new google.maps.ImageMapType( myAerialOptions );
map.overlayMapTypes.insertAt(1, AerialMapType);
var panorama = new google.maps.StreetViewPanorama(map.getDiv());
panorama.setVisible(false);
panorama.set('enableCloseButton', true);
map.setStreetView(panorama);
panorama.setPosition(centerMap);
setMarkers(map, sites);
setZoom(map, sites);
infowindow = new google.maps.InfoWindow({
content: "Loading..."
});
googleEarth = new GoogleEarth(map);
google.maps.event.addListenerOnce(map, 'tilesloaded', addOverlays);
}
/*
This functions sets the markers (array)
*/
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var site = markers[i];
var siteLatLng = new google.maps.LatLng(site[1], site[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: site[0],
zIndex: site[3],
html: site[4],
// Markers drop on the map
animation: google.maps.Animation.DROP,
icon: 'http://www.virtualbc.ca/knoxmountain/icons/'+site[5]+'.png',
shadow: iconShadow
});
gmarkers.push(marker);
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
/*
Set the zoom to fit comfortably all the markers in the map
*/
function setZoom(map, markers) {
var boundbox = new google.maps.LatLngBounds();
for ( var i = 0; i < markers.length; i++ )
{
boundbox.extend(new google.maps.LatLng(markers[i][1], markers[i][2]));
}
map.setCenter(boundbox.getCenter());
map.fitBounds(boundbox);
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i-1], "click");
// gmarkers[i].setAnimation(null);
// gmarkers[i-1].setAnimation(google.maps.Animation.BOUNCE);
// value = i-1;
}
google.maps.event.addDomListener(window, 'load', init);
The questions:
How to make the tiles visible in Google Earth API?
or how to display a KML file ONLY in Google Earth Tab?
is there any way to run code only when Google Earth Tab is selected?
Thanks in advance.

There are a few ways to do what you're aiming for. To clarify the original question somewhat, this page is using the GoogleEarth part of the Google Maps v3 Utility Library, so my answers will take advantage of its features.
First, it is possible to run code only when the Google Earth view is selected. You can test at any time if you're in the Earth view by checking the current MapTypeId. The utility library provides a custom id, which indicates the user is using the Earth view if
map.getMapTypeId() === GoogleEarth.MAP_TYPE_ID
That's the passive test. To be notified any time the user switches to the Earth map type, you can register an event listener like this:
google.maps.event.addListener(map, 'maptypeid_changed', function() {
if (map.getMapTypeId() === GoogleEarth.MAP_TYPE_ID) {
// using the Earth plugin, can run custom code
} else {
// some other map type (roadmap, satellite, etc)
}
});
Finally, the utility library only synchronizes KML overlays between Maps and Earth if you add them via the Maps API. If you instead add the KML directly to the Earth plugin, it will only be displayed in the Earth plugin, not in the regular Maps view. To do this, you need a reference to the actual plugin instance, which you can get from the utility library by
var ge = googleEarth.getInstance();
(this is using your code where googleEarth is the name of the instance you created with the utility library). At this point, you can use the plugin as you normally would with the Earth API. See this example of loading KML, for instance: Fetch Good KML

Related

Markercluster Doubling Markers

For some reason, Markercluster is doubling the markers in a group. For example, when I click on a group I see four individual markers instead of two. The names are duplicated too. I looked through other posts but am still confused by this. Thanks!
<script>
var mapData = <?php echo wp_json_encode($mapData); ?>;
var map = L.map('map').setView([40, 0], 2);
var markers = new L.MarkerClusterGroup();
L.mapbox.accessToken = 'myToken';
var geocoder = L.mapbox.geocoder('mapbox.places');
for ( var i = 0; i < mapData.length; i++ )
{
geocoder.query(mapData[i].city, showLoc);
}
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=myToken', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(map);
function showLoc (err, data) {
var city = data.results.query.join(' ');
for ( var i = 0; i < mapData.length; i++ )
{
if ( mapData[i].city.toLowerCase() === city ) {
var marker = L.marker(new L.LatLng(data.latlng[0], data.latlng[1]), {
icon: L.mapbox.marker.icon({'marker-color': 'c70c2b'}),
title: mapData[i].name
});
//new L.Marker([data.latlng[0], data.latlng[1]], 2)
marker.bindPopup("<strong>" + mapData[i].name + "</strong>")
markers.addLayer(marker);
}
}
markers.addTo(map);
}
Think I figured it out. Very simple fix. Had to move var markers = new L.MarkerClusterGroup(); in my showLoc (err, data) function. I think it has to do with declaring it after the map tiles load. Not sure though.

How do I add Marker Clusters to my Google Map?

I can't figure out how to add Marker Clusters to this map. It's used with Wordpress, so that the user can add locations to it from the Wordpress dashboard. I'm pretty new to Google API and I'm not having success with any examples that I find. Any help is appreciated!
<?php // Index template
get_header(); ?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div class="twelve column">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="intro">
<?php the_excerpt(); ?>
<hr>
</div>
<?php the_content(); ?>
<header class="clearfix"></header>
<div id="mapcanvas"></div>
<?php
// For creating multiple, customized loops.
// http://codex.wordpress.org/Class_Reference/WP_Query
$custom_query = new WP_Query('post_type=locations'); // exclude category 9
while($custom_query->have_posts()) : $custom_query->the_post(); ?>
s <?php if(get_field('link')): ?>
<div>
<?php while(has_sub_field('link')): ?>
<div>
<p><?php the_sub_field('url'); ?></p>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>
<?php
function get_single_term($post_id, $taxonomy)
{
$terms = wp_get_object_terms($post_id, $taxonomy);
if(!is_wp_error($terms)) {
return ''.$terms[0]->name.'';
}
}
$i = 0;
// For creating multiple, customized loops.
// http://codex.wordpress.org/Class_Reference/WP_Query
$custom_query = new WP_Query('post_type=location&posts_per_page=-1');
while($custom_query->have_posts()) : $custom_query->the_post();
$title = get_the_title(); // Location title
$map = get_field('location'); // ACF location contains address and coordinates
$terms = strip_tags( get_the_term_list( $post->ID, 'distributors', '', ' & ' )); // Get distributor terms and rm links
$info = '<strong>' . $title . '</strong><br>' . $map['address']; // Info window content
$link = get_field('link');
if($link){
$info .= '<br>'. $link .'';
}
$location[$i][0] = $title; // Store the post title
$location[$i][1] = $map['coordinates']; // Store the ACF coordinates
$location[$i][2] = json_encode($info); // Store info window content
$location[$i][3] = strip_tags( get_single_term( $post->ID, 'distributors' )); // Get first term for marker icon
$i ++;
endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>
<script>
var geocoder;
var map;
$(function initialize() {
geocoder = new google.maps.Geocoder();
// Center map on our main location
var myLatLng = new google.maps.LatLng(41.583013,-93.63701500000002);
var bounds = new google.maps.LatLngBounds();
// https://developers.google.com/maps/documentation/javascript/styling
// Create an array of styles.
var styles = [
{
stylers: [
{ saturation: -99.9 }
]
}
];
// Create a new StyledMapType object, passing it the array of styles,
// as well as the name to be displayed on the map type control.
var styledMap = new google.maps.StyledMapType(styles, {name: 'exile'});
// Create a map object, and include the MapTypeId to add
// to the map type control.
var mapOptions = {
mapTypeId: 'roadmap',
center: myLatLng,
zoom: 14,
disableDefaultUI: false,
scrollwheel: true,
draggable: true
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("mapcanvas"), mapOptions);
map.setTilt(45);
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('exile', styledMap);
map.setMapTypeId('exile');
// Marker icons
typeObject = {
"Others" : {
"icon" : new google.maps.MarkerImage('http://exilebrewing.com/site/img/beer-mug.png', new google.maps.Size(18,26), new google.maps.Point(0,0), new google.maps.Point(9,26)),
"shadow" : new google.maps.MarkerImage('http://maps.google.com/mapfiles/shadow50.png', new google.maps.Size(40,34))
}
}
// http://wrightshq.com/playground/placing-multiple-markers-on-a-google-map-using-api-3/
// Multiple Markers
var markers = [
["Exile Brewing Co", 41.583013,-93.63701500000002,"Others"],
<?php
if (count($location)>0) {
foreach ($location as $key => $value){
if ($key < (count($location)-1)){
echo '["' . $location[$key][0] . '",' . $location[$key][1] . ',"' . $location[$key][3] . '"], ' . "\n";
} else {
echo '["' . $location[$key][0] . '",' . $location[$key][1] . ',"' . $location[$key][3] . '"]';
}
}
}
?>
];
// Info Window Content
var infoWindowContent = [
["<strong>Exile Brewing Co.</strong><br>1514 Walnut Street, Des Moines"],
<?php
if (count($location)>0) {
foreach ($location as $key => $value){
if ($key < (count($location)-1)) {
echo '[' . $location[$key][2] . '], ' . "\n";
} else {
echo '[' . $location[$key][2] . ']';
}
}
}
?>
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]); // ACF coordinates
var icon = typeObject[markers[i][3]]['icon'];
var shadow = typeObject[markers[i][3]]['shadow'];
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: icon,
shadow: shadow
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
//map.fitBounds(bounds);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(15);
google.maps.event.removeListener(boundsListener);
});
});
</script>
<div id="panel">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
<footer class="clearfix"></footer>
<?php endwhile;?>
<?php endif; ?>
</div>
</div>
<?php get_footer(); ?>
Some
There can be three kind of clustering of markers as follows
Grid-Based Clustering
Grid-based clustering is probably the most common approach for clustering markers. It will divide the map into a grid and group all markers within each square into a cluster. Although an efficient technique, it has some obvious limitations since it can lead to unwanted results. Two markers that are really close together but in separate squares will, for example, not be grouped into the same cluster.
Distance-Based Clustering
This technique looks at each individual marker and checks whether it’s nearby other markers. If it’s close enough to another marker, the two of them will be grouped into a cluster.
Distance-based clustering also has its drawbacks. Since the clusters will appear at random
locations depending on where a cluster is formed they may not make sense for the user.
Regional Clustering
A third technique is regional clustering. What this means is that you define different geographical regions, such as counties or states. All markers in each region will be grouped into a cluster. You also define at which zoom level the cluster will break up into separate markers (or smaller clusters). The advantage of this technique is that you can create clusters that make more sense to the user. The drawback is that it requires more effort and can’t as easily be automated as the other clustering techniques.
Example
Shows the complete code. When you run this page, it will add 100 markers at random
locations at the visible part of the map. If you want to try adding a different number of markers, just change the number in the for loop.
(function() {
window.onload = function(){
// Creating a map
var options = {
zoom: 3,
center: new google.maps.LatLng(37.09, -95.71),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
// Getting the boundaries of the map
var bounds = map.getBounds();
// Getting the corners of the map
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
// Calculating the distance from the top to the bottom of the map
var latSpan = northEast.lat() - southWest.lat();
// Calculating the distance from side to side
var lngSpan = northEast.lng() - southWest.lng();
// Creating a loop
for (var i = 0; i < 100; i++) {
// Creating a random position
var lat = southWest.lat() + latSpan * Math.random();
var lng = southWest.lng() + lngSpan * Math.random();
var latlng = new google.maps.LatLng(lat, lng);
// Adding a marker to the map
new google.maps.Marker({
position: latlng,
map: map
});
}
});
};
})();
Try this
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(13.696516,-89.208765);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var contentString = '<h1>Aditivos de El salvador</h1><p>33 Av. Sur #661, Colonia Flor Blanca, San Salvador El Salvador.</p>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var image = '<?php echo bloginfo('template_url'); ?>/images/iconmapa.png';
var beachMarker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image
});
google.maps.event.addListener(beachMarker, 'click', function() {
infowindow.open(map,beachMarker);
});
}
</script>

Can I modify this code to detect whether a street view image is available in Google Maps API?

I have to admit, I wing it a bit with Google Maps API. A lot of copy and pasting and basic edits. This code works really well unless a street view image is not available. What is the easiest way to detect no image and hid the pano div? Or the other way round, display it if there is an image:
function googleMap() {
var geocoder = new google.maps.Geocoder();
if (geocoder) {
alert('<?php echo $phoneDirectory->Address; ?>');
geocoder.geocode({ 'address': '<?php echo $phoneDirectory->Address; ?>' }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var googleLat = results[0].geometry.location.lat();
var googleLong = results[0].geometry.location.lng();
//alert(googleLat + ", " + googleLong);
var fenway = new google.maps.LatLng(googleLat,googleLong);
var mapOptions = {
center: fenway,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById('map_canvas'), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 0,
pitch: 0
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
map.setStreetView(panorama);
// **** ADDED TO GET WORKING!!! *****
var client = new google.maps.StreetViewService();
client.getPanoramaByLocation(fenway, 50, function(result, status) {
if (status == "ZERO_RESULTS") {
// Hide street view div
$('#pano').css("display", "none");
}
});
googleMapLoaded = true;
}
else {
alert('No results found: ' + status);
}
});
}
}
Check this
If there are no nearby panoramas the result is ZERO_RESULTS

Assign Google Fusion Tables Data to display Google Maps InfoBubble

I am trying to create a map with data exported from my Google Fusion Tables. The problem is, I have so many data to be displayed including text and images. And I want to create info windows with tabs.
How will I be possibly display infobubble when I click on a marker? The code that I have now to retrieve Google Fusion Tables data is:
layer = new google.maps.FusionTablesLayer({
map: map,
query: {
select: "col1",
from: "xxxxxxxxxxxxxxxxxxxxxxxxxx"
},
options: {
styleId: 3,
templateId: 3
}
});
I already looked for ways to get this problem solved and I found this sample http://jsbin.com/efobeg/13/edit.
EDIT:
Here's the code that I am currently working on.
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 3,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'col7',
from: '10NhYAiDivSpUnjvNsOwZVTEPV-RjhRGmyEOGjs4'
},
map: map,
suppressInfoWindows: true,
options: {
styleId: 2,
templateId: 3
}
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(layer, 'click', function(e) {
var name = e.row['restaurantname'].value;
var cuisine = e.row['cuisine'].value;
var address = e.row['full_address'].value;
var rating = e.row['rating'].value;
if (rating != "") {
if (rating == 1) {
rating = "http://exrx.net/test_weewok2/1.png";
} else if (rating == 2) {
rating = "http://exrx.net/test_weewok2/2.png";
} else if (rating == 3) {
rating = "http://exrx.net/test_weewok2/3.png";
} else if (rating == 4) {
rating = "http://exrx.net/test_weewok2/4.png";
} else {
rating = "http://exrx.net/test_weewok2/5.png";
}
} else {
rating = "http://exrx.net/test_weewok2/1.png";
}
var review = e.row['review'].value;
if (review == "") {
review = "No one has reviewed this place.";
}
var contentString = [
'<div class="tabs">',
'<ul>',
'<li><span>Overview</span></li>',
'<li><span>Review</span></li>',
'<li><span>Images</span></li>',
'</ul>',
'<div id="tab-1">',
'<b>' + name + '</b><img src="' + rating + '" /><br>',
'<font size=1><b>' + address + '</b></font></center>',
'<p align=justify><font size=1>' + cuisine + '</font>',
'</p>',
'</div>',
'<div id="tab-2">',
'<p align=justify><i>"' + review + '"</i></p>',
'</div>',
'<div id="tab-3">',
'<p>Images will be displayed here.</p>',
'</div>',
'</div>'
].join('');
infowindow.setContent(contentString);
infowindow.setPosition(e.latLng);
infowindow.open(map);
$(".tabs").tabs({ selected: 0 });
});
}
Screenshot:

Open InfoWindow for each polygon google maps V3

Hope someone can help me with this issue.
I'm trying to open an info windows on click for each polygon that my users created.
I used the same code for a marker and works well but i couldn't make it work for each polygon.
Any thoughts on how to solve this problem?
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h2>Test</h2>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
// Show Areas
<?php foreach ($field->result() as $f):?>
// Create an array with the coordanates of each area
var field<?=$f->id?>Coords = [
<?php $latlng=$this->resources_data->field_latlng($f->id);?>
<?php foreach ($latlng->result() as $point):?>
new google.maps.LatLng(<?=$point->lat?>, <?=$point->lng?>),
<?php endforeach;?>
];
// Create a polygon with the points of the area
var area<?=$f->id?>=new google.maps.Polygon({
paths: area<?=$f->id?>Coords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
// Add the area to the map.
area<?=$f->id?>.setMap(map);
google.maps.event.addListener(area<?=$f->id?>,'click',function(){
infowindow.open(map,area<?=$f->id?>)
});
<?php endforeach;?>
You can't use the same form of InfoWindow.open for a polygon as you use for a marker (there is no marker to pass in).
From the documentation
open(map?:Map|StreetViewPanorama, anchor?:MVCObject)
Return Value: None
Opens this InfoWindow on the given map. Optionally, an InfoWindow can be associated with an anchor. In the core API, the only anchor is the Marker class. However, an anchor can be any MVCObject that exposes a LatLng position property and optionally a Point anchorPoint property for calculating the pixelOffset (see InfoWindowOptions). The anchorPoint is the offset from the anchor's position to the tip of the InfoWindow.)
You need to specifically set the place you want it to open when you call the open method (the latlng of the click is usually a good choice) with InfoWindow.setPosition().
Example
code snippet:
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function initialize() {
var geolib = google.maps.geometry.spherical;
var myOptions = {
zoom: 20,
center: new google.maps.LatLng(32.738158, -117.14874),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
bounds = new google.maps.LatLngBounds();
var polygon1 = new google.maps.Polygon({
map: map,
path: [geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, 0),
geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, 120),
geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, -120)
],
name: "polygon1"
});
google.maps.event.addListener(polygon1, 'click', function(event) {
var contentString = "name:" + this.name + "<br>" + event.latLng.toUrlValue(6);
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
for (var i = 0; i < polygon1.getPath().getLength(); i++) {
bounds.extend(polygon1.getPath().getAt(i));
}
var polygon2 = new google.maps.Polygon({
map: map,
path: [geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, 180),
geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, 60),
geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, -60)
],
name: "polygon2"
});
google.maps.event.addListener(polygon2, 'click', function(event) {
var contentString = "name:" + this.name + "<br>" + event.latLng.toUrlValue(6);
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
for (var i = 0; i < polygon2.getPath().getLength(); i++) {
bounds.extend(polygon2.getPath().getAt(i));
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
function createClickablePoly(poly, html, label, point) {
gpolys.push(poly);
if (!point && poly.getPath && poly.getPath().getLength && (poly.getPath().getLength > 0) && poly.getPath().getAt(0)) {
point = poly.getPath().getAt(0);
}
var poly_num = gpolys.length - 1;
if (!html) {
html = "";
} else {
html += "<br>";
}
var length = poly.Distance();
if (length > 1000) {
html += "length=" + poly.Distance().toFixed(3) / 1000 + " km";
} else {
html += "length=" + poly.Distance().toFixed(3) + " meters";
}
for (var i = 0; i < poly.getPath().getLength(); i++) {
html += "<br>poly[" + poly_num + "][" + i + "]=" + poly.getPath().getAt(i);
}
html += "<br>Area: " + poly.Area() + " sq meters";
// html += poly.getLength().toFixed(2)+" m; "+(poly.getLength()*3.2808399).toFixed(2)+" ft; ";
// html += (poly.getLength()*0.000621371192).toFixed(2)+" miles";
var contentString = html;
google.maps.event.addListener(poly, 'click', function(event) {
infowindow.setContent(contentString);
if (event) {
point = event.latLng;
}
infowindow.setPosition(point);
infowindow.open(map);
// map.openInfoWindowHtml(point,html);
});
if (!label) {
label = "polyline #" + poly_num;
}
label = "<a href='javascript:google.maps.event.trigger(gpolys[" + poly_num + "],\"click\");'>" + label + "</a>";
// add a line to the sidebar html
// side_bar_html += '<input type="checkbox" id="poly'+poly_num+'" checked="checked" onclick="togglePoly('+poly_num+');">' + label + '<br />';
}
body,
html {
height: 100%;
width: 100%;
}
<script src="https://maps.google.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<table border="1" style="height:100%; width:100%">
<tr>
<td>
<div id="map_canvas" style="width:100%; height:100%"></div>
</td>
<td width="200">
<div id="report"></div>
</td>
</tr>
</table>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 45.15492713361847, lng: 15.40557861328125}
});
var polygons = [{name: 'first name', coordinates:[{lat:45.15492713361847,lng:15.40557861328125},{lat:45.07933920973809,lng:15.5291748046875},{lat:45.01918507438175,lng:15.43304443359375},{lat:45.07933920973809,lng:15.3204345703125}]}];
// foreach your polygons
for (var i = 0; i < polygons.length; i++) {
var item = polygons[i];
var coors = item["coordinates"];
var name = item["name"];
var Polygon = new google.maps.Polygon({
path: coors,
strokeColor: '#66b3ff',
strokeOpacity: 0.8,
strokeWeight: 5,
editable: false,
fillColor: 'blue',
fillOpacity: 0.5,
});
Polygon.setMap(map);
// call function to set window
attachPolygonInfoWindow(Polygon, coors, name);
}
}
function attachPolygonInfoWindow(polygon, coors, html)
{
polygon.infoWindow = new google.maps.InfoWindow({
content: html
});
polygon.infoWindow.setPosition(getHighestWindowPosition(coors));
google.maps.event.addListener(polygon, 'mouseover', function () {
polygon.infoWindow.open(map, polygon);
});
google.maps.event.addListener(polygon, 'mouseout', function () {
polygon.infoWindow.close();
});
}
// function to get highest position of polygon to show window nice on top
function getHighestWindowPosition(coors) {
var lat = -5000, lng = 0, i = 0, n = coors.length;
for (; i !== n; ++i) {
if (coors[i].lat > lat) {
lat = coors[i].lat;
lng = coors[i].lng;
}
}
return {lat: lat, lng: lng};
}
</script>

Resources