Google maps infowindow display kml object name and link - javascript

I have some working code to display a KML layer on Google maps. When you click on the various parts of the layer their respective name pops up in an info window.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
// Load Google Maps API
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXX&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(51.875696, -0.624207);
var mapOptions = {
zoom: 6,
center: myLatlng
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var kmlLayer = new google.maps.KmlLayer({
url: 'http://XXXXXXX.org/gliding/grid3.kml',
suppressInfoWindows: false,
map: map
});
google.maps.event.addListener(kmlLayer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.name;
showInContentWindow(text);
});
function showInContentWindow(text) {
var sidediv = document.getElementById('content-window');
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width:100%; height:100%; float:left"></div>
</body>
</html>
I would like the info window to also contain a link to a page with the same name as object clicked on. For example if the user clicks on a shape in the KML layer called Tom the info window says Tom Click Here. If the user clicks the link they are taken to www.XYZ.com/Tom.
I'm sure this is quite simple, but I'm new to javascript and can't get it to work.

This is more a hack than a solution (which means google could change a property name and this would stop working.
However, here you go
google.maps.event.addListener(kmlLayer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.name;
kmlEvent.featureData.infoWindowHtml += 'Click Here';
showInContentWindow(text);
});

Related

Change icon of marker clicked when you have multiple markers

I am trying to change the marker icon when the marker is clicked the problem is the code below only changes the last marker I added to the map not the marker I am clicking on, so if I only had one marker it would work fine. I tried looking it up but all the examples I could find only work with 1 marker loaded in the map. I tried the listener two different ways the second one is commented out below the the first way and both just change the icon of the the last marker loaded.
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 95%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 95%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap"
async defer></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
<script>
let markers = [];
let map;
function loadMarkers(ssStr)
{
$.getJSON(ssStr, function(data) {
for (var i = 0; i < data.feed.entry.length; i++)
{
var latLng = new google.maps.LatLng(data.feed.entry[i]['gsx$lat']['$t'],
data.feed.entry[i]['gsx$long']['$t']);
var marker = new google.maps.Marker({
position: latLng,
map: map,
label:data.feed.entry[i]['gsx$structure']['$t'],
icon: { url: "http://maps.google.com/mapfiles/ms/icons/red.png" }
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
//Change the marker icon
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green.png');
});
/* marker.addListener("click", (event) => {
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green.png');
}); */
}
var latLng = new google.maps.LatLng(data.feed.entry[0]['gsx$lat']['$t'],
data.feed.entry[0]['gsx$long']['$t']);
map.setCenter(latLng);
});
}
function initMap() {
console.log("initMap");
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(41.5, -72)
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
loadMarkers("http://spreadsheets.google.com/feeds/list/SSID/od6/public/values?alt=json");
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

google map mouseevent in firefox shows incorrect coordinates

I have a google map api page that does not return the correct coordinates from the mouse event in firefox when the map div is not at the top left (0,0) of the browser window. If I put any css padding or margin on the map div, the mouseevent origin in google maps still starts from the top left of the browser window and not the map div. The mouseevent works correctly in IE & Chrome returning the correct lat/lng but not Firefox. Anyone have any suggestions to correct?
I created a very simple example at http://jsfiddle.net/fNPvf/15426/ that shows the coordinates as the mouse is moved over the map. You can see at the top left of the map image, the coordinates should be 0,0 but Firefox showing 50,50. The infowindow shows the correct lat/lng of the map center and you can see the difference in coordinates (50 pixel shift to top left) when you move the mouse to that point.
<html>
<head>
<meta charset="utf-8">
<style>
body {font:12px arial; margin:0px}
#map {
height:400px;
width:400px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
coord = new google.maps.LatLng(38.939201, -94.747640)
function initialize() {
var mapOptions = {
zoom: 16,
center: coord
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
google.maps.event.trigger(map, 'resize');
var coordInfoWindow = new google.maps.InfoWindow();
coordInfoWindow.setContent('38.939201, -94.747640');
coordInfoWindow.setPosition(coord);
coordInfoWindow.open(map);
google.maps.event.addListener(map, "mousemove", function (event) {
document.getElementById("footer").innerHTML = "Mouse X Y:" + event.pixel.toString() + " - Lat Lng:" + event.latLng.toString() + "<br />"
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map" style="margin-left:50px;margin-top:50px;"></div>
<div id="footer" style="margin-left:50px; padding:10px;"></div>
</body>
</html>
Solution:
Add parameter v=3 once calling the google maps api. The fiddle provided by user4974882 is calling 3.exp - doesn't work.
Works:
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
Live example
Doesn't work correctly:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
Live example
(both fiddles from user4974882)
Background:
The problem occured with Firefox Version 39. The Mozilla-team implemented some new functionality regarding offsetX/Y (https bugzilla.mozilla.org/show_bug.cgi?id=69787). Unfortunately the Google Maps API already somehow plays around with that (https code.google.com/p/gmaps-api-issues/issues/detail?id=8278) and so - once FF39 was rolled out - the problem popped up.
Problem with latest release of FF v39. Worked previously in v38.0.5.
I can confirm that the following is bugged, given a map with a fixed size and a 64px margin, "Hello World!" will only appear when you place the mouse pointer at -64,-64 relative to the marker. It appears that inside Maps, the pointer position is offset by the x/y of the map element relative to the top left corner of Firefox' client area
This issue has appeared in the last few days
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
#map-canvas
{
width: 640px;
height: 480px;
margin: 64px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
When creating a marker use the option {optimized:false}. It solves the issue in firefox 39.0.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
#map-canvas
{
width: 640px;
height: 480px;
margin: 64px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!',
optimized: false
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
As stated - this bug crept in with FF 39.
In your example, replace the v=3.exp parameter with just v=3
So it would be
src="https://maps.googleapis.com/maps/api/js?v=3"

Can't get google map to display on wordpress page

I am new to google maps api and am using it to put a map on my wordpress page and get the location of the user. So far, I have kept the following code in my header.php file with myapikey replaced with my actual api key.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?libraries=places&key=myapikey"></script>
I also have a wordpress page with the following code. This code works when I keep it on a html file. However, when I put this code on my wordpress page, I don't even get the map to show. I am using Google Maps API v3 Geolocation. Could someone please help me.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta charset="utf-8">
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0 }
#map-canvas { height: 100%; width: 100%; top: -100px;}
</style>
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
//Html five geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: "HTML5 is used."
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
You can't paste the complete document into the editor, what you put into the editor is expected to be te content of your page, it may be almost anything that you would put into the of a HTML-page(no html, head and body).
script and style always include either via the header/footer of the theme or via a plugin.

issue in adding click event in a Geolocation

I am working on HTML5 and javascript. and i am developing an application which finds the user's location using google map and the i am trying to add a click event on the user's location so that when they click they click the message "click here" they must be directed to a new html page. any help or idea would be appreciated.
and here is my code :
<!DOCTYPE html>
<html>
<head>
<title>Getting Geolocation for Weather Details</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<style type="text/css">
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
#media print {
html, body {
height: auto;
}
#map_canvas {
height: 650px;
}
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var map;
function initialize() {
var myOptions = {
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'click here'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
Does this help?
Replace text with an anchor tag.
use content : '<a href="https://www.google.com">click here<a>' in place of content : 'click here' as in -
var infowindow = new google.maps.InfoWindow({
map : map,
position : pos,
content : '<a href="https://www.google.com">click here<a>'
});
In your case you can put your page link in place of https://www.google.com.

Detecting Google map being closed and Google map infowindow being closed

I am trying to create a map dialog which allows the user to select his or her desired location.
I have a working example located at http://jsfiddle.net/HCUPa/1/, and the source code is below.
When the infowindow is closed (by clicking the X on the infowindow), how do I remove the associated marker? Do I then need to remove the infowindows name from the array, and if so, how?
Also, when the map (or dialog and then the map) is closed, how do I detect it being closed, and should I be cleaning up any resources, and if so what and how?
I attempted to use addListeners for both as shown in my example, but it isn't working.
Lastly, not really my formal question, but I would appreciate any advise whether I am generally doing this correct. This was my first attempt of the Google map api, and I am still a JavaScript novice, and would appreciate any suggestions, criticize, etc.
Thank you
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
#googleMap { height: 100%;width: 100%;}
div.modify-title-bar div.ui-dialog-titlebar {border:0;background-image:none;background-color:transparent;padding:0;margin:0;}
#dialog-map,div.modify-title-bar {padding:0;margin:0;}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link type="text/css" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false"></script>
<script type="text/javascript">
function createMap(geocoder,myCenter,address) {
var map = new google.maps.Map(document.getElementById("googleMap"),{center:myCenter,zoom:5,mapTypeId:google.maps.MapTypeId.ROADMAP});
var marker = new google.maps.Marker({position: myCenter,map: map,});
var infowindow = new google.maps.InfoWindow({content: '<span>'+address+'</span><br><button class="accept">Select Address</button>'});
infowindow.open(map,marker);
google.maps.event.addListener(map, 'close', function(event) {
//How do I detect map closing, what and how should I clean up? Maybe move to dialog close?
alert('close map');
delete geocoder,myCenter,address,map,marker,infowindow;
});
google.maps.event.addListener(map, 'click', function(event) {
marker.setMap(null);
marker = new google.maps.Marker({
position: event.latLng,
map: map,
});
geocoder.geocode({location: event.latLng}, function(GeocoderResult, GeocoderStatus) {
infowindow.close();
infowindow = new google.maps.InfoWindow({content: '<span>'+GeocoderResult[0].formatted_address+'</span><br><button class="accept">Select Address</button>'});
infowindow.open(map,marker);
});
google.maps.event.addListener(infowindow,'closeclick',function(){
//How do I detect if infowindow is closed? Do I then need to remove the infowindows name from the array, and if so, how?
alert('Remove marker');
marker.setMap(null);
});
});
}
$(function(){
$("#googleMap").on("click", "button.accept", function(){
$('#address').val($(this).parent().children('span').eq(0).text());
$("#dialog-map").dialog('close');
});
$("#findIt").click(function(){$("#dialog-map").dialog("open");return false;});
$("#dialog-map").dialog({
autoOpen : false,
resizable : false,
height : 500,
width : 800,
modal : true,
dialogClass : 'modify-title-bar',
open : function() {
var address=$.trim($('#address').val()),
geocoder=new google.maps.Geocoder,
LatLng,
//Default LatLng
Ya=47.6204901, Za=-122.34964839999998,
//Give default address to limit geocoder calls
default_address='400 Broad Street, Seattle, WA 98109, USA';
if(address) {
geocoder.geocode({address: address}, function(GeocoderResult, GeocoderStatus) {
if (GeocoderStatus=='OK') {
LatLng=GeocoderResult[0].geometry.location;
}
else {
LatLng=new google.maps.LatLng(Ya,Za);
adderss=default_address;
}
createMap(geocoder,LatLng,address);
});
}
else {
LatLng=new google.maps.LatLng(Ya,Za);
createMap(geocoder,LatLng,default_address);
}
}
});
});
</script>
</head>
<body>
<button id="findIt">Find it on a map</button>
<input id="address" type="text" value="1600 Pennsylvania Avenue Northwest Washington, DC">
<div id="dialog-map" title="Select a location">
<div id="googleMap"></div>
</div>
</body>
</html>
Create a new function that listens for the infowindow close event
function infowindowClose(infowindow, marker) {
google.maps.event.addListenerOnce(infowindow, 'closeclick', function() {
marker.setMap(null);
});
}
Call that everytime you create a new infowindow.
Working Demo
You are doing well for your first time using the API. If you want more than one marker and infobox then you will need to make a few changes, otherwise it's fine.

Categories

Resources