google maps loading map on button click - loading markers with another button - google-maps-api-3

I'm trying to load markers on the click of a button, but somewhere i'm missing something. 1. map pulls out and loads with one button click. 2. markers load with the click of a different button. here's what i have:
<!DOCTYPE>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
<link rel="stylesheet" type="text/css" href="
<?php
$stylesarray = array("field");
echo $stylesarray[mt_rand(0,count($stylesarray)-1)];
?>.css">
<link rel="shortcut icon" href="images/favicon.ico">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=xxx&sensor=false"></script>
<script type="text/javascript">
var map = null;
$(document).ready(function(){
var lat=document.getElementById("latitude");
var long=document.getElementById("longitude");
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
lat.value=+position.coords.latitude;
long.value=+position.coords.longitude;
}
});
function load() {
var map = new google.maps.Map(document.getElementById("mapcontainer"), {
center: new google.maps.LatLng(20,0),
zoom: 3,
styles: mapstyle,
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
maxZoom: 8,
minZoom: 3,
mapTypeId: 'roadmap'
});
}
function getmarkers(){
downloadUrl("markers.php", function(data) {
//alert ("it works");
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var info = markers[i].getAttribute("info");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var date = markers[i].getAttribute("date");
var html = "<div id='tooltip'><div id='tiptext'>" + info
+ "<div id='number'>" + id + "</div>"
+ "<div id='date'>" + date + "</div>"
+ "</div></div>";
var marker = new google.maps.Marker({
map: map,
position: point,
icon: 'images/mapicon.png'
});
createTooltip(marker, html);
}
});
</script>
</head>
<body>
<div id="mapcontainer">
<form>
<input type="button" id="map" onClick="load()"></input>
</form>
<form>
<input type="button" onClick="getmarkers()"></input>
</form>
</body>
</html>
xml sample:
<markers>
<marker id="330" info="blahblah" date="2012-10-03" latitude="20.00" longitude="-81.00"/>
</markers>

Your map variable is local to your initialize function. It won't be accessible to the code that loads the markers.
Try defining it globally (outside of any functions):
var map = null;
Then initialize it in your load function
function load() {
map = new google.maps.Map(document.getElementById("mapcontainer"), {
The problem (after syntax errors) with your posted code is that the getmarkers function is local to the load function. It needs to be global to be called by an HTML element click function.
Live working version based off your example code

It seems like you do not declare the map variable in the global scope. Only in the load function scope, declare it as a global variable and it should work.
var map = null; // Declaring map in the global scope
function load() {
// map references to global scope
map = new google.maps.Map(document.getElementById("mapcontainer"), {
...
}
downloadUrl("markerinfo.php", function(data) {
...
var marker = new google.maps.Marker({
map: map, // map references to global scope
position: point,
icon: 'images/mapicon.png'
});
createTooltip(marker, html);
}
});
Try wrapping the DownloadUrl function call in another function and call that instead.
<input type="button" id="markerload" onClick="getMarkers()"></input>
function getMarkers() {
downloadUrl("markerinfo.php", function(data) {
...
});
}

function getmarkers() is designed to retrieve all markers with a for loop
for (var i = 0; i < markers.length; i++) {
To load one marker at a time you will need to increment it for each button click
Ie Var i =0 globally
Increment i at end of getmarkers() i++
You should stop the increments after the last member of array when it gets to markers.length

Related

Centering Google Maps from a marker

Im triying to create a map with a marker from a position taken from a database. I succeed creating the map using this tutorial. The problem is that i have to enter manually the center position when i create the map.
¿Is there a way to center the map using the marker?. The code that im using is the following:
<!DOCTYPE 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 type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></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("loadposition.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("Latitud")),
parseFloat(markers[i].getAttribute("Longitud")));
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>
Also my XML generated file looks like this:
<markers>
<marker Latitud="-33.449148" Longitud="-70.552886"/>
</markers>
Thanks a lot!
I used this in an app after adding the marker. Might help you.
bounds = new google.maps.LatLngBounds();
bounds.extend(marker.position);
if (!bounds.isEmpty())
map.panTo(bounds.getCenter());
Original idea was to find the center of a bunch of markers, so this might be overkill.

Event listener to delete individual markers when they are clicked, only acts on last created marker

Hello and thanks in advance for your help!
The following test code:
1) Uses PHP to get lat/lng data from a mySQL database, and then uses that data to form a JavaScript array with initialization data. WORKS FINE.
2) Uses the initialized JavaScript array to create markers. WORKS FINE.
3) Allows (left) clicks to create new markers (more code will be added later to add those new marker locations back into the database). WORKS FINE.
4) Allows RIGHT-clicks to delete a marker using marker.setMap(null) - either the preloaded markers from the database, or newly created user markers. USER MARKERS DELETE PROPERLY, PRE-LOADED MARKERS DO NOT DELETE PROPERLY, AS DESCRIBED BELOW.
5) Both the preloaded markers, and the newly created ones are stored in the array "markers" using the statement markers.push(marker). SEEMS TO BE OK.
Everything works, except the right-click deletion of the PRELOADED markers. (The right-click deletion of user created markers works fine.) Any right-click on any preloaded marker, only deletes the LAST preloaded marker. It's as if the delete event listener were outside and after the loop that sets the preloaded markers, but it is inside that loop.
I think the faulty section is the one with the leading comment "show prev clicks in database". Any ideas would be greatly appreciated! I'm very new at Google Maps API v3, so it's probably something obvious that I'm just missing or misunderstanding. Thanks again!
<!DOCTYPE html>
<html>
<head>
<title>Marker Test</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas, #map_canvas {
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
<?
// Generate JavaScript array initialization from database
$username="REDACTED";
$password="REDACTED";
$database="REDACTED";
$con=mysql_connect(localhost,$username,$password);
#mysql_select_db($database,$con) or die( "Unable to select database");
$query="SELECT * FROM pool where (record_id >= 1765) AND (record_id <= 1769)";
/*
$query="SELECT * FROM pool where (record_id <= '$marker_end') AND (record_id >= '$marker_start')";
$query="SELECT * FROM pool where session = '$session'";
*/
$result=mysql_query($query,$con);
$length=mysql_num_rows($result);
$length_count=1;
if ($result) {
echo "var PreviousClicks = [\n";
while($row = mysql_fetch_array($result)) {
$_lat=$row['google_lat'];
$_lng=$row['google_lng'];
$_record_id=$row['record_id'];
echo "{\n";
echo "lat: $_lat,\n";
echo "lng: $_lng,\n";
echo "title: \"$_record_id\"\n";
echo "}";
if($length_count<$length) {echo ",\n";} else {echo "\n";}
$length_count++;
} // end while
echo "];";
} // end if
mysql_close();
?>
</script>
<script type="text/javascript">
var map;
var markers = [];
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
title: "A",
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
markers.push(marker);
} //end addMarker function
function initialize() {
// currently manual center initialization
var startLoc = new google.maps.LatLng(33.037380,-117.090431);
var mapOptions = {
zoom: 16,
center: startLoc,
mapTypeId: google.maps.MapTypeId.TRAFFIC
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
// show prev clicks in database ------------------------------------------------------------------
for (i = 0; i < PreviousClicks.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(PreviousClicks[i].lat, PreviousClicks[i].lng),
title: PreviousClicks[i].title,
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
markers.push(marker);
} // end for
// end "show prev clicks in database" section ----------------------------------------------------
} // end function initialize
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas">
</div>
</body>
</html>
Inside a marker's event handler, this refers back to the marker. Therefore :
this.setMap(null);
will remove the marker from the map.
But more can be done with this code. In particular :
Avoid repeating code by using addMarker() to add both new and previous markers.
When markers are removed, also remove them from the markers array.
Both can be achieved as follows :
function addMarker(event) {
var marker = new google.maps.Marker({
position: event.latLng,
title: event.title || "A",
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
this.setMap(null);
//Remove the marker from the markers array.
for(i=0; i<markers.length; i++) {
if(markers[i] == this) {
removed = markers.splice(i, 1);
break;
}
}
});
markers.push(marker);
}
function initialize() {
...
google.maps.event.addListener(map, 'click', addMarker);
...
for (i = 0; i < PreviousClicks.length; i++) {
addMarker({
latLng: new google.maps.LatLng(PreviousClicks[i].lat, PreviousClicks[i].lng);
title: PreviousClicks[i].title
});
}
}

Marker do not appear when I try to integrate Google Maps into an existing web page

I previously prepare a javascript that shows some marker downloaded in JSON format, from a webservice.
The code is:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MAP</title>
<link type="text/css" href="css/style.css" rel="stylesheet" media="all" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3.8"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="map_bar.js"></script>
</head>
<body>
<h1>MAPPA</h1>
<div id="map"></div>
</body>
</html>
that calls the map_bar.js:
(function() {
window.onload = function() {
// Creating a new map
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(80.650535,41.886146),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Creating a global infoWindow object that will be reused by all markers
function createPoints(json){
var infoWindow = new google.maps.InfoWindow();
// Looping through the JSON data
for (var i = 0, length = json.locations.length; i < length; i++) {
var data = json.locations[i],
latLng = new google.maps.LatLng(data.lat, data.long);
console.log(data.long);
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.nombre,
icon: 'beer.png'
});
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function() {
info = data.nombre+'<br/>'+data.offerta+'<br/>'+data.horario;
infoWindow.setContent(info); //esto escibe las info
infoWindow.open(map, marker);
});
})
(marker, data);
}
}
// Get the JSON data from PHP script
var json ;
$.getJSON("http://mywebservice.php").done(function(data) {
console.log(data);
json = data;
createPoints(json);
});
}
})();
It works, but the problem appears when I trying to integrate that in an existing webpage.
I have some sections and putting the same code in my "map section", the map appears but not markers.
The console.log(data) into the getJSON method not give back the point. It strange because the same code works in a "stand alone" page.
Any idea about that?
Thanks in advance.
jquery getJSON is subject to the same origin policy, a sub-domain is not the same domain as the main domain.
Using a relative reference to a file in the sub-domain fixes the issue.

click listeners conflict w/ infowindow

I'm attempting to create a map that allows users to report a trailwork
problem by clicking and filling a form in an infowindow (similar to
seeclickfix.com). I haven't built in the php/SQL that will actually
save the information provided by the user yet.
The problem: I have a button in the html of my infowindow for users to
submit information and close the window. Instead of just closing the
window though, my event listener for new markers receives clicks
through the infowindow, creating an unwanted marker behind the button.
Google avoids this problem somehow; no click is registered on their
top right-exit 'x'.
I've attempted to create a Boolean signal variable ('infopen') to let
my addMarker function know if an infowindow is open, but it's not
functioning.... Any ideas why?
Any other suggestions regarding the code would be appreciated!
(My task is creating a system to organizing and store multiple
infowindows/markers...)
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Reporter </title>
<script type="text/javascript" src="http://maps.google.com/maps/
api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var marker;
var markers = [];
var infowindow;
var infopen = false;
var edit = true;
var pos = new google.maps.LatLng(44.021, -71.831102);
function initialize() {
var mapOptions = {
zoom: 14,
center: pos,
mapTypeControl: true,
panControl: false,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var table = "<table>" +
"<tr><td>Problem:</td> <td><input type='text'
id='prob'/> </td> </tr>" +
"<tr><td>Description:</td> <td><input type='text'
size='30' id='desc'/></td> </tr>" +
"<tr><td align=right ><input type='button'
value='Save & Close' onclick='saveData()' /></td>" +
"<td><input type='button' value='Cancel & Delete'
onclick='cancel()' /></td></tr>";
infowindow = new google.maps.InfoWindow({
content: table
});
google.maps.event.addListener(map, "click", function(event) {
addMarker(event.latLng);
});
} //end initialize
// Add a marker to the map and push to the array, open an infowindow listener.
function addMarker(location) {
if (editon.editT[0].checked) edit = true; //check 'edit' radio buttons
if (editon.editT[1].checked) edit = false;
alert('infopen is ' + infopen);
if (edit== true && infopen== false) {
//if edit toggle is selected and infowindow not open
marker = new google.maps.Marker({
position: location, //from event.latLng
map: map,
draggable: true,
});
markers.push(marker); //add to markers array
google.maps.event.addListener(marker, "click", function() {
//listener for infowindow
infowindow.open(map, marker);
infopen = true; // stop the creation of new markers *in theory...
//alert('infopen is ' + infopen);
});
}// end if
} //end addMarker()
// Sets the map on all markers in the array. (only used when clearing)
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Deletes all markers in the array by removing references to
them.
function deleteOverlays() {
setAllMap(null);
markers = [];
}
//would passes along info to php... not yet
function saveData() {
infowindow.close();
infopen = false; //reallow marker creation from click
}
//closes window and clears marker
function cancel() {
infowindow.close();
infopen = false; // reallow marker creation ***click still
heard by event listener***
marker.setMap(null); //just clears from map
}
</script>
</head>
<body onload="initialize()">
<br> </br>
<form name="editon"> Turn on editing:
<input type="radio" name="editT" value='true' checked/>Yes
<input type="radio" name="editT" value='false' />No
</form>
<div id="map_canvas" style="width:100%; height:70%"></div>
<p>If too cluttered:
<input onclick="deleteOverlays();" type=button value="Clear Map"/>
</body>
</html>
My contrived hack: add a setTimeout() around infowindow.close(). There is a rationale, explained below.
function saveData() {
setTimeout(function() { infowindow.close(); }, 100);
}
//closes window and clears marker
function cancel() {
setTimeout(function() { infowindow.close(); marker.setMap(null); }, 100);
}
100 ms seems reasonable. Strangely, setting the marker to a null map in cancel() also has to be timed out. I don't think you need infopen anymore.
I got the idea from this code sample:
http://code.google.com/apis/maps/articles/phpsqlinfo_v3.html
In this sample, the infoWindow is only closed (in a callback) after a database request is made and ensuring the response was good. Of course, this must take some milliseconds. So, under these assumptions, once you have your DB part working, you can replace the ugly setTimeout and everything should work! :)

Why Marker Manager doesn't work?

I would use MarkerManager to group neighboring marker in one, I tested an example but it does not work. Different markers are displayed well, but they are not together when they should. The manager is not working as it should, I do not understand why.
<html>
<head>
<title>Test GMap - MarkerManager</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/src/markermanager.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js"></script>
</head>
<body>
<div id="my-map" style="width:100%;height:700px"></div>
<script>
var maCarte = '';
function initialisation(){
var centreCarte = new google.maps.LatLng(47.389982, 0.688877);
var optionsCarte = {
zoom: 5,
center: centreCarte,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
maCarte = new google.maps.Map(document.getElementById("my-map"), optionsCarte);
// Create a new instance of the MarkerManager
var mgr = new MarkerManager(maCarte);
google.maps.event.addListener(mgr, 'loaded', function() {
console.log('loaded Map');
// Create marker array
var markers = [];
// Loop to create markers and adding them to the MarkerManager
for(var i = 0; i < 50; i += 0.1) {
var marker = new google.maps.Marker({position: new google.maps.LatLng(47.389982 + i, 0.688877 + i)});
markers.push(marker);
}
//var markerCluster = new MarkerClusterer(map, markers);
// Add the array to the MarkerManager
mgr.addMarkers(markers, 8);
// Refresh the MarkerManager to make the markers appear on the map
mgr.refresh();
});
}
google.maps.event.addDomListener(window, 'load', initialisation);
</script>
</body>
Can someone help me?
thank you very much
Your page works for me, but the markers are not immediately visible when the page loads. This is because of the zoom setting you have on line 34:
mgr.addMarkers(markers, 8);
if you set that to a lower number (say, 4) the markers will be visible when zoomed further out.

Resources