I wrote the following code to display markers. There are 2 buttons which show Next or Previous Infowindow for markers. But problem is that InfoWindows are not shown using google.maps.event.trigger
Can someone help me with this problem. Thank you.
Here is code:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Common Loader</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var infowindow;
var map;
var bounds;
var markers = [];
var markerIndex=0;
function initialize() {
var myLatlng = new google.maps.LatLng(41.051407, 28.991134);
var myOptions = {
zoom: 5,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
markers = document.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(markers[i].getAttribute("name"), latlng, markers[i].getAttribute("phone"), markers[i].getAttribute("distance"));
}
rebound(map);
}
function createMarker(name, latlng, phone, distance) {
var marker = new google.maps.Marker({position: latlng, map: map});
var myHtml = "<table style='width:100%;'><tr><td><b>" + name + "</b></td></tr><tr><td>" + phone + "</td></tr><tr><td align='right'>" + distance + "</td></tr></table>";
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: myHtml});
infowindow.open(map, marker);
});
return marker;
}
function rebound(mymap){
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng"))));
}
mymap.fitBounds(bounds);
}
function showNextInfo()
{
if(markerIndex<markers.length-1)
markerIndex++;
else
markerIndex = 0 ;
alert(markers[markerIndex].getAttribute('name'));
google.maps.event.trigger(markers[markerIndex],"click");
}
function showPrevInfo()
{
if(markerIndex>0)
markerIndex--;
else
markerIndex = markers.length-1 ;
google.maps.event.trigger(markers[markerIndex],'click');
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:400px; height:300px"></div>
<markers>
<marker name='Name1' lat='41.051407' lng='28.991134' phone='+902121234561' distance=''/>
<marker name='Name2' lat='40.858746' lng='29.121666' phone='+902121234562' distance=''/>
<marker name='Name3' lat='41.014604' lng='28.972256' phone='+902121234562' distance=''/>
<marker name='Name4' lat='41.012386' lng='26.978350' phone='+902121234562' distance=''/>
</markers>
<input type="button" onclick="showPrevInfo()" value="prev"> <input type="button" onclick="showNextInfo()" value="next">
</body>
</html>
this is how i'm doing it
hope it can help ;)
/**
* map
*/
var myLatlng = new google.maps.LatLng(39.980278, 4.049835);
var myOptions = {
zoom: 10,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
}
var map = new google.maps.Map(document.getElementById('mapa'), myOptions);
var infoWindow = new google.maps.InfoWindow();
var markerBounds = new google.maps.LatLngBounds();
var markerArray = [];
function makeMarker(options){
var pushPin = new google.maps.Marker({map:map});
pushPin.setOptions(options);
google.maps.event.addListener(pushPin, 'click', function(){
infoWindow.setOptions(options);
infoWindow.open(map, pushPin);
});
markerArray.push(pushPin);
return pushPin;
}
google.maps.event.addListener(map, 'click', function(){
infoWindow.close();
});
function openMarker(i){
google.maps.event.trigger(markerArray[i],'click');
};
/**
*markers
*/
makeMarker({
position: new google.maps.LatLng(39.943962, 3.891220),
title: 'Title',
content: '<div><h1>Lorem ipsum</h1>Lorem ipsum dolor sit amet<div>'
});
openMarker(0);
This code doesn't work because it is triggering click event on markers[markerIndex] which is not map marker but information about DOM element with tag marker.
To get it running you have to add global array which will contain list of map markers:
var markerList = [];
Change initialize() function to push map marker to that list in for loop:
markerList.push(marker);
Change functions showNextInfo() and showPrevInfo() to trigger event on map marker:
//google.maps.event.trigger(markers[markerIndex], "click");
google.maps.event.trigger(markerList[markerIndex], "click");
Related
I'm using the Google Maps API to capture the zoom level when the user clicks on the map. I would then like to increase the zoom level by 1, but I'm having trouble doing this and I'm getting multiple console.log entries when I run this in the browser.
Here's the script in question:
var map = null;
function initialize() {
var myOptions = {
zoom: 12,
scaleControl: true,
streetViewControl: false,
center: new google.maps.LatLng(-28.8413400, 153.4384050),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-28.8413400, 153.4384050),
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/blue.png',
title: ''
});
var point = new google.maps.LatLng(-27.7028557, 153.0120736);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 2</p>', icon)
var point = new google.maps.LatLng(-29.8089498, 152.8230076);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 4</p>', icon)
var point = new google.maps.LatLng(-26.6564235, 153.0586826);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 4</p>', icon)
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(100, 20)
});
function createMarker(latlng, html, icon) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: icon,
map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoomLevel = map.getZoom();
console.log(zoomLevel);
});
google.maps.event.addListener(map, "click", function(event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
var newCentre = latitude + ', ' + longitude;
var currentZoomLevel = map.getZoom();
console.log("currentZoomLevel: " + currentZoomLevel);
var zoomLevel = parseInt(currentZoomLevel, 10) + 1;
console.log("zoomLevel: " + zoomLevel);
});
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Markers</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.33&key=myKeyHere"></script>
<style type="text/css">
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map-canvas"></div>
</body>
</html>
When I look at the console log I can see multiple entries of the following:
[Log] currentZoomLevel: 12
[Log] zoomLevel: 13
It looks like it's generating an entry for each marker that I have on the map. For example if I have 3 markers I'm getting 6 entries in the console.log, but I'm not sure why this is happening?
Simply move your map event listeners outside of your createMarker function.
I also modified:
declared infowindow as a global variable so that it can be accessed in both functions
merged the 2 map click event listeners into one
var map = null;
var infowindow;
function initialize() {
var myOptions = {
zoom: 12,
scaleControl: true,
streetViewControl: false,
center: new google.maps.LatLng(-28.8413400, 153.4384050),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
myOptions);
infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(100, 20)
});
google.maps.event.addListener(map, 'click', function(event) {
infowindow.close();
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
var newCentre = latitude + ', ' + longitude;
var currentZoomLevel = map.getZoom();
console.log("currentZoomLevel: " + currentZoomLevel);
var zoomLevel = parseInt(currentZoomLevel, 10) + 1;
console.log("zoomLevel: " + zoomLevel);
});
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoomLevel = map.getZoom();
console.log(zoomLevel);
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-28.8413400, 153.4384050),
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/blue.png',
title: ''
});
var point = new google.maps.LatLng(-27.7028557, 153.0120736);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 2</p>', icon)
var point = new google.maps.LatLng(-29.8089498, 152.8230076);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 4</p>', icon)
var point = new google.maps.LatLng(-26.6564235, 153.0586826);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 4</p>', icon)
}
function createMarker(latlng, html, icon) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: icon,
map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
initialize();
#map-canvas {
height: 200px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
So I have some working code which fetches results from my DB and displays them on a Google map. I also have some code which uses my location to place a marker on a Google map.
My issue is that when I add them together the page loads the results from the DB then I accept geoloaction and it centers the map to my location but doesn't display my marker and also removes the markers for the DB results.
Here is the DB result code:
<!DOCTYPE html >
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("/Models/phpsqlajax_genxml2.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
This is my geolocation code:
// Check if user support geo-location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geolocpoint = new google.maps.LatLng(latitude, longitude);
var map = new google.maps.Map(document.getElementById('nearMeMap'), {
zoom: 11,
scaleControl: false,
scrollwheel: false,
center: geolocpoint,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
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][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
// Place a marker
var geolocation = new google.maps.Marker({
position: geolocpoint,
map: map,
title: 'Your Location',
icon: 'https://mt.google.com/vt/icon?psize=20&font=fonts/Roboto-Regular.ttf&color=ff330000&name=icons/spotlight/spotlight-waypoint-blue.png&ax=44&ay=48&scale=1&text=%E2%80%A2'
});
});
}
Also I get this in the console:
ReferenceError: locations is not defined
for (i = 0; i < locations.length; i++) {
As the ReferenceError already says, you do not have the variable locations defined in your geolocation code.
I have just started working with the Google Maps API, and am trying to display multiple markers across an array of data.
However I am getting a marker for just the first location in my list, which I guess means my loop isn't working properly, but I am not getting any errors to work from.
var mapOptions = {
center: centralLatlng,
zoom: 2
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var cdnLocations = [
['LondonMarker', 51.500, 0.1167],
['NewYorkMarker', 40.7127, -74.0059],
['TokyoMarker', 35.6895, 139.6917],
['BerlinMarker', 52.5167, 13.3833],
['ParisMarker', 48.8567, 2.3508],
['MadridMarker', 40.4000, 3.6833],
]
for (var i = 0; i < cdnLocations.length; i++) {
var cdnLocations = cdnLocations [i]
var marker = new google.maps.Marker({
position: new google.maps.LatLng (cdnLocations[1], cdnLocations[2]),
map: map,
});
}
Check this out:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locations = [
['LondonMarker', 51.500, 0.1167],
['NewYorkMarker', 40.7127, -74.0059],
['TokyoMarker', 35.6895, 139.6917],
['BerlinMarker', 52.5167, 13.3833],
['ParisMarker', 48.8567, 2.3508],
['MadridMarker', 40.4000, 3.6833],
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 1,
center: new google.maps.LatLng(35.68, 139.69),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
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][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
Here a jsfiddle example:
http://jsfiddle.net/m2htynto/
My assignment asks to place multiple markers on the map based on an xml document that we need to parse. I've done the parsing, but I'm having from trouble figuring out how to put the lat and long elements into the new marker object. My code:
function loadPoint(){
// var newHTML= "<div style=\"padding:5px;border:solid 1px red\">";
// new_lat = escapeText($(this).find("latitude").number();
// new_long = escapeText($(this).find("longitude"));
// newHTML += new_lat + "," + new_long;
// newHTML += "</div>";
// $("body").append(newHTML);
var latlong= new google.maps.LatLng($(this).find("latitude"),$(this).find("longitude"));
var marker = new google.maps.Marker({
map: map,
position: latlong
})
}
function parser(data) {
$(data).find("item title").each(loadDescription);
$(data).find("item latitude").each(loadLat);
$(data).find("item longitude").each(loadLong);
$(data).find("item").each(loadPoint);
}
function myBadLoadFunction(myXMLHttpRequest,myErrorMessage,myErrorThrown) {
alert('status: ' + myErrorMessage + '\n' + myXMLHttpRequest.responseText);
}
var map;
var centerPoint = new google.maps.LatLng(53.608803,-1.497327);
function initializeMap(){
var myOptions = {
zoom: 8,
center: centerPoint,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map_canvas').get(0), myOptions);
In my head this makes sense...putting the parsed data as the params for creating a new latlng, but it does nothing so..
Try arranging your declarations first.
var map; //declare it here
function initialize(){
var centerPoint = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: centerPoint
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
}
function loadPoint(){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locations = [
[-33.890542, 151.274856],
[-33.923036, 151.259052],
[-34.028249, 151.157507],
[-33.80010128657071, 151.28747820854187],
[-33.950198, 151.259302]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
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]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
Hey guys I just started a new project with google maps. I'm a newbie in both javascript and google maps API.
UPDATED:
What I'm trying to do is to add a informationWindow to each marker with different content. So when the marker is clicked, the content for that specific marker pops up.
Right now only the 4th element pops up. I need so that every marker pops up with information.
Is there any other way of doing this?
Thanks in advance,
UPDATED:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Marker Animations Loop</title>
<link href="https://developers.google.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var myLatlng = new google.maps.LatLng(53.014783, -95.097656);
var iterator = 0;
var neighborhoods = new Array(
new Array("test1","49.165206","-122.665443"),
new Array("test2","49.14476","-121.98544"),
new Array("test3","49.162063","-122.667675"),
new Array("test4","48.455005","-123.54155"),
new Array("test5","51.038156","-114.035339")
);
var markers = [];
function initialize()
{
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
/*for (var i = 0; i < neighborhoods.length; i++)
{
markers[iterator] = new google.maps.Marker(
{
position: neighborhoods[iterator],
map: map,
title: 'Hello World!'
}
);
iterator++;
};*/
var infowindow = new google.maps.InfoWindow({
});
for(var i = 0; i < neighborhoods.length; i++)
{
var marker = new google.maps.Marker(
{
position: new google.maps.LatLng(neighborhoods[i][1], neighborhoods[i][2]),
map: map,
title: neighborhoods[i][0]
}
);
var test = neighborhoods[i][0];
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.open(map,marker);
infowindow.setContent(test);
});
}
};
</script>
</head>
<body onload="initialize();">
<div id="map_canvas" style="width: 1000px; height: 700px;">map div</div>
<!--button id="drop" onclick="drop()">Drop Markers</button-->
</body>
</html>
Here is an example which I ported to the Google Maps API v3 from Mike Williams' Google Maps API (v2) tutorial that has multiple markers with unique infowindows, it uses function closure to associate the infowindow content with the marker.
The final version is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Marker Animations Loop</title>
<link href="https://developers.google.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var myLatlng = new google.maps.LatLng(53.014783, -95.097656);
var iterator = 0;
var neighborhoods = new Array(
new Array("test1","49.165206","-122.665443"),
new Array("test2","49.14476","-121.98544"),
new Array("test3","49.162063","-122.667675"),
new Array("test4","48.455005","-123.54155"),
new Array("test5","51.038156","-114.035339")
);
var markers = [];
function initialize()
{
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
infowindow = new google.maps.InfoWindow({
});
for(var i = 0; i < neighborhoods.length; i++)
{
var marker = new google.maps.Marker(
{
position: new google.maps.LatLng(neighborhoods[i][1], neighborhoods[i][2]),
map: map,
title: neighborhoods[i][0],
html: neighborhoods[i][0],
animation: google.maps.Animation.DROP
}
);
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent(this.html);
infowindow.open(map,this);
});
}
};
</script>
</head>
<body onload="initialize();">
<div id="map_canvas" style="width: 1000px; height: 700px;">map div</div>
</body>
</html>