Save Button Not attached to the Right InfoWindow, Google Map - javascript

After adding a delete function and adding my markers into an array the save button/ save function is no longer attached to the right infowindow on my google map.
If I open two infowindows, enter the info in both, then click save on the first one I opened it will update the last infowindow created with "You submitted" and it will save it twice. I tried a few different things based on different stack overflow posts including adding an iterator around the initialization of my infowindow and also adding an external function for adding a marker, but this did not work. I also made sure my global variables (like map) are declared before initializing. I am a nube that has been struggling for days.
I'm sure the issue surrounds my confusion about how the infowindow is attached to the markers in the array. My code is in the snippet below.
var markers = [];
var uniqueId = 1;
var marker;
var infowindow;
var map;
var html;
function initialize() {
var mapOptions = {
zoom: 8,
center: {
lat: 48.591130,
lng: -119.682349
},
mapTypeControlOptions: {
mapTypeIds: ['roadmap']
}
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
//Attach click event handler to the map.
google.maps.event.addListener(map, 'click', function(e) {
//Determine the location where the user has clicked.
var location = e.latLng;
//Create a marker and placed it on the map.
var marker = new google.maps.Marker({
position: location,
map: map,
});
//Set unique id
marker.id = uniqueId;
uniqueId++;
markers.push(marker);
//Attach click event handler to the marker.
google.maps.event.addListener(marker, "click", function(e) {
html = "<p style='color:#173e43;font-size:120%;font-weight:bold;text-align:center; width:150pxs; margin-top: 2px; margin-bottom:4px' >Add A Comment</p>" +
"<table>" +
"<tr><td>Issue/Idea:</td> <td> <textarea rows='1' cols='26' id='name' style='height: 30px; width:150px' name='reply'></textarea></td> </tr>" +
"<tr><td>Address:</td> <td><input type='text' id='address' style='width:150px'/></td> </tr>" +
"</td></tr>";
html += "<tr><td><input type = 'button' value = 'Delete' onclick = 'DeleteMarker(" + marker.id + ");' value = 'Delete' /></td>" +
"<td><input type='button' value='Submit' onclick='saveData(" + marker.id + ")'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
infowindow.setContent(html);
infowindow.open(map, marker);
});
//Add marker to the array.
markers.push(marker);
});
};
function DeleteMarker(id) {
//Find and remove the marker from the Array
for (var i = 0; i < markers.length; i++) {
if (markers[i].id == id) {
//Remove the marker from Map
markers[i].setMap(null);
//Remove the marker from array.
markers.splice(i, 1);
return;
}
}
};
function saveData(id) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].id == id) {
var name = escape(document.getElementById("name").value);
var address = escape(document.getElementById("address").value);
var latlng = markers[i].getPosition();
var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
"&lat=" + latlng.lat() + "&lng=" + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length >= 1) {
document.getElementById("message").innerHTML = "Location added. Contents: name=" + name +", address=" + address+ " latlng=" +latlng;
}
});
infowindow.setContent("You submitted Contents: name=" + name +", address=" + address+ " latlng=" +latlng);
}
}
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
function doNothing() {}
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<div id="dvMap" style="width: 1000px; height: 490px"></div>
<div id="message"></div>

Ok, so I moved the push statement so that it is pushing the marker to the array after I declare the infowindow. This stopped the save function from saving the html contents multiple times. So the save is working great now, the only problem is my ability to update the right infowindow with the message "You submitted..."
It is still just updating the last infowindow I opened with that message.
var markers = [];
var uniqueId = 1;
var marker;
var infowindow;
var map;
var html;
function initialize() {
var mapOptions = {
zoom: 8,
center: {
lat: 48.591130,
lng: -119.682349
},
mapTypeControlOptions: {
mapTypeIds: ['roadmap']
}
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
//Attach click event handler to the map.
google.maps.event.addListener(map, 'click', function(e) {
//Determine the location where the user has clicked.
var location = e.latLng;
//Create a marker and placed it on the map.
var marker = new google.maps.Marker({
position: location,
map: map,
});
//Set unique id
marker.id = uniqueId;
uniqueId++;
//Attach click event handler to the marker.
google.maps.event.addListener(marker, "click", function(e) {
html = "<p style='color:#173e43;font-size:120%;font-weight:bold;text-align:center; width:150pxs; margin-top: 2px; margin-bottom:4px' >Add A Comment</p>" +
"<table>" +
"<tr><td>Issue/Idea:</td> <td> <textarea rows='1' cols='26' id='name' style='height: 30px; width:150px' name='reply'></textarea></td> </tr>" +
"<tr><td>Address:</td> <td><input type='text' id='address' style='width:150px'/></td> </tr>" +
"</td></tr>";
html += "<tr><td><input type = 'button' value = 'Delete' onclick = 'DeleteMarker(" + marker.id + ");' value = 'Delete' /></td>" +
"<td><input type='button' value='Submit' onclick='saveData(" + marker.id + ")'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
infowindow.setContent(html);
infowindow.open(map, marker);
});
//Add marker to the array.
markers.push(marker);
});
};
function DeleteMarker(id) {
//Find and remove the marker from the Array
for (var i = 0; i < markers.length; i++) {
if (markers[i].id == id) {
//Remove the marker from Map
markers[i].setMap(null);
//Remove the marker from array.
markers.splice(i, 1);
return;
}
}
};
function saveData(id) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].id == id) {
var name = escape(document.getElementById("name").value);
var address = escape(document.getElementById("address").value);
var latlng = markers[i].getPosition();
var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
"&lat=" + latlng.lat() + "&lng=" + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length >= 1) {
document.getElementById("message").innerHTML = "Location added. Contents: name=" + name +", address=" + address+ " latlng=" +latlng;
}
});
infowindow.setContent("You submitted Contents: name=" + name +", address=" + address+ " latlng=" +latlng);
}
}
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
function doNothing() {}
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<div id="dvMap" style="width: 1000px; height: 490px"></div>
<div id="message"></div>

Related

Content window on marker

I try this code for plotting data on google map and I plot it successfully currently there is 2 marker when i click on marker then content window is open but second marker content window is not open
this is the result on console
{"response":[["B9","5",27.13197”,”34.95 "],["L330","5",”27.06688”,”34.864"]}"
image
image
when i click on second marker then content window not open
Here is my code :
success: function (result) {
var d = JSON.parse(result.d).response;
console.log(JSON.parse(result.d).response);
console.log(JSON.stringify(result.d));
$("#tabledata").empty();
if (d.length > 0) {
$("#tabledata").append(
"<thead><tr><th>RegNo</th><th>Status</th><th>Longitude</th><th>Latitude</th></tr></thead>");
for (var i = 0; i < d.length - 1; i++) {
if (d[i] !== null) {
$("#tabledata").append("<tbody><tr><td>" +
d[i][0] + "</td> <td>" +
d[i][1] + "</td> <td>" +
d[i][2] + "</td> <td>" +
d[i][3] + "</td></tr></tbody>");
Status = d[i][2];
debugger;
RegNo = d[i][0];
latit = d[i][4];
longi = d[i][3];
}
}
}
else {
$("#tabledata").hide();
}
alert(d.length);
var map;
//var markers;
debugger;
var latlng = new google.maps.LatLng(24.0895898, 67.0998546);
debugger;
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
debugger;
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
debugger;
debugger;
for (i = 0; i < d.length - 1; i++) {
var data = d[i]
var myLatlng = new google.maps.LatLng(d[i][4], d[i][3]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Click me'
});
}
debugger;
for (i = 0; i < d.length - 1; i++){
var infowindow = new google.maps.InfoWindow({
content: 'RegNo:' + d[i][0] + '<br>Status:' + d[i][2] + '<br>Lat:' + d[i][4] + 'Long:' + d[i][3]
});
}
debugger;
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker, data);
});
}
Your problem is this line here:
infowindow.open(marker, data, map);
The InfoWindow open function takes 1 or 2 arguments, and it should be like this:
infowindow.open(map, marker);

Undefined on tohere and fromhere message windows in google maps API V3

I have a map loading on my site (I am not a java coder this is code i have found on the internet). I have figured out mostly how to get it working for my needs. However when you click on the To Here or From Here links instead of populating the address from the marker over it shows as undefined in the message window. I am sure this is something easy I am missing but any help is appreciated
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
var htmls = [];
// arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];
// global "map" variable
var map = null;
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function initialize() {
var location = new google.maps.LatLng(33.3440017700195, -111.96068572998);
var mapOptions = {
center: location,
zoom: 14,
scrollwheel: true
};
map = new google.maps.Map(document.getElementById("map"),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("map"));
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var image = {
url: 'http://maps.google.com/mapfiles/ms/micons/green.png'
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(33.34396, -111.960606),
map: map,
animation: google.maps.Animation.DROP,
icon: image,
Title: 'Fusion Formulations<br>1430 W Auto Drive<br>Tempe, AZ 85284'
});
var i = gmarkers.length;
latlng = location;
// The info window version with the "to here" form open
to_htmls[i] = html +
'<b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
'<br>Start address:<form action="javascript:getDirections()">' +
'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
'<INPUT value="Get Directions" TYPE="button" onclick="getDirections()"><br>' +
'Walk <input type="checkbox" name="walk" id="walk" /> Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
'<input type="hidden" id="daddr" value="' + latlng.lat() + ',' + latlng.lng() +
'"/>';
// The info window version with the "from here" form open
from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
'<br>End address:<form action="javascript:getDirections()">' +
'<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
'<INPUT value="Get Directions" TYPE="SUBMIT"><br>' +
'Walk <input type="checkbox" name="walk" id="walk" /> Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
'<input type="hidden" id="saddr" value="' + latlng.lat() + ',' + latlng.lng() +
'"/>';
// The inactive version of the direction info
var html = marker.getTitle() + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <a href="javascript:fromhere(' + i + ')">From here<\/a>';
var contentString = html;
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(15);
map.setCenter(marker.getPosition());
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
htmls[i] = html;
}
google.maps.event.addDomListener(window, 'load', initialize);
// ===== request the directions =====
function getDirections() {
// ==== Set up the walk and avoid highways options ====
var request = {};
if (document.getElementById("walk").checked) {
request.travelMode = google.maps.DirectionsTravelMode.WALKING;
} else {
request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
}
if (document.getElementById("highways").checked) {
request.avoidHighways = true;
}
// ==== set the start and end locations ====
var saddr = document.getElementById("saddr").value;
var daddr = document.getElementById("daddr").value;
request.origin = saddr;
request.destination = daddr;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else alert("Directions not found:" + status);
});
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
// functions that open the directions forms
function tohere(i) {
//gmarkers[i].openInfoWindowHtml(to_htmls[i]);
infowindow.setContent(to_htmls[i]);
infowindow.open(map, gmarkers[i]);
}
function fromhere(i) {
//gmarkers[i].openInfoWindowHtml(from_htmls[i]);
infowindow.setContent(from_htmls[i]);
infowindow.open(map, gmarkers[i]);
}
You aren't defining the html variable which is used for that first field of the HTML in the infowindow.
// The info window version with the "to here" form open
to_htmls[i] = html +
'<b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
// ...
'"/>';
That should be the HTML you want displayed, in the case or your example, this works for me:
html = 'Fusion Formulations<br>1430 W Auto Drive<br>Tempe, AZ 85284<br>';
Also, you have an issue with the title property of the marker. You are assigning the Title property, which is not the same (javascript is case sensitive).
(Also, FYI, the MarkerOptions title property doesn't support HTML markup, so you shouldn't include HTML markup in the title string)
proof of concept fiddle
code snippet:
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
var htmls = [];
// arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];
// global "map" variable
var map = null;
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function initialize() {
var location = new google.maps.LatLng(33.3440017700195, -111.96068572998);
var mapOptions = {
center: location,
zoom: 14,
scrollwheel: true
};
map = new google.maps.Map(document.getElementById("map"),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("map"));
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var image = {
url: 'http://maps.google.com/mapfiles/ms/micons/green.png'
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(33.34396, -111.960606),
map: map,
animation: google.maps.Animation.DROP,
icon: image,
Title: 'Fusion Formulations<br>1430 W Auto Drive<br>Tempe, AZ 85284'
});
html = 'Fusion Formulations<br>1430 W Auto Drive<br>Tempe, AZ 85284<br>';
var i = gmarkers.length;
latlng = location;
// The info window version with the "to here" form open
to_htmls[i] = html +
'<b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
'<br>Start address:<form action="javascript:getDirections()">' +
'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
'<INPUT value="Get Directions" TYPE="button" onclick="getDirections()"><br>' +
'Walk <input type="checkbox" name="walk" id="walk" /> Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
'<input type="hidden" id="daddr" value="' + latlng.lat() + ',' + latlng.lng() +
'"/>';
// The info window version with the "from here" form open
from_htmls[i] = html + '<a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
'<br>End address:<form action="javascript:getDirections()">' +
'<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
'<INPUT value="Get Directions" TYPE="SUBMIT"><br>' +
'Walk <input type="checkbox" name="walk" id="walk" /> Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
'<input type="hidden" id="saddr" value="' + latlng.lat() + ',' + latlng.lng() +
'"/>';
// The inactive version of the direction info
var html = marker.getTitle() + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <a href="javascript:fromhere(' + i + ')">From here<\/a>';
var contentString = html;
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(15);
map.setCenter(marker.getPosition());
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
htmls[i] = html;
}
google.maps.event.addDomListener(window, 'load', initialize);
// ===== request the directions =====
function getDirections() {
// ==== Set up the walk and avoid highways options ====
var request = {};
if (document.getElementById("walk").checked) {
request.travelMode = google.maps.DirectionsTravelMode.WALKING;
} else {
request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
}
if (document.getElementById("highways").checked) {
request.avoidHighways = true;
}
// ==== set the start and end locations ====
var saddr = document.getElementById("saddr").value;
var daddr = document.getElementById("daddr").value;
request.origin = saddr;
request.destination = daddr;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else alert("Directions not found:" + status);
});
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
// functions that open the directions forms
function tohere(i) {
//gmarkers[i].openInfoWindowHtml(to_htmls[i]);
infowindow.setContent(to_htmls[i]);
infowindow.open(map, gmarkers[i]);
}
function fromhere(i) {
//gmarkers[i].openInfoWindowHtml(from_htmls[i]);
infowindow.setContent(from_htmls[i]);
infowindow.open(map, gmarkers[i]);
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
(note the actual directions request doesn't work in the code snippet due to a security restriction: Blocked form submission to 'javascript:getDirections()' because the form's frame is sandboxed and the 'allow-forms' permission is not set., it does work in the fiddle)

Unique Info boxes attached to individual markers on google maps api

I am trying to code a feature for my site that will allow a user to click down on the google map, a marker will appear. When the marker has appeared the user will click said marker and be able to fill in some information. I have this working.
However when the user clicks on another marker to go and edit it, the window for the previous marker does not open anymore. How can I edit an info window, save it, then edit another info window and be able to open the info window at any time of clicking?
Here is my JS code:
function initialize() {
var latlng = new google.maps.LatLng(54.5, -7.0);
var options = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), options);
var html = "<table>" +
"<tr><td>Country:</td> <td><input type='text' id='country'/> </td> </tr>" +
"<tr><td>City:</td> <td><input type='text' id='city'/></td> </tr>" +
"<tr><td>Duration:</td> <td><input type='text' id='duration'/></td> </tr>" +
"<tr><td>Category:</td> <td><select id='category'>" +
"<option value='city' SELECTED>City Break</option>" +
"<option value='beach'>Beach Holiday</option>" +
"<option value='romantic'>Romantic Holiday</option>" +
"<option value='activity'>Activity Holiday</option>" +
"<option value='site'>Site Seeing</option>" +
"</select> </td></tr>" +
"<tr><td></td><td><input type='button' value='Save & Close' onclick='saveData()'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
infowindow.setContent(html);
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
}
function saveData() {
var country = escape(document.getElementById("country").value);
var duration = escape(document.getElementById("duration").value);
var category = document.getElementById("category").value;
var latlng = marker.getPosition();
var url = "phpsqlinfo_addrow.php?country=" + country + "&city" + city + "&duration=" + duration +
"&category=" + category + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length >= 1) {
infowindow.close();
document.getElementById("message").innerHTML = "Location added.";
}
});
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
You should place the initialization of the infowindow inside the addListener as well as create a local variable for marker and infowindow.
google.maps.event.addListener(map, "click", function(event) {
var marker = new google.maps.Marker({
position: event.latLng,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: html
});
infowindow.setContent(html);
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
}

Google map, lat/lng on loaded points

I am loading points from a mysql database into a google map. These are, for example, traffic construction locations.
My question is, how do I get the lat/lng to update on loaded points as each point is dragged? You can see the modified code below. I want to be able to drag any / all points to a new location and the lat/lng to be updated in the lat/lng fields in the infowindow form so it can be submitted and updated in the database.
I am able to get this when adding a new point but not loading multiple. Can I somehow get this to work with individual loaded points? Not getting anything to work.
I can provide the "working" map if needed.
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.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 latlng = markers[i].getPosition();
var latitude = markers[i].getAttribute("lat");
var longitude = markers[i].getAttribute("lng");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<table class='tg'>" +
"<tr>" +
"<th class='tg-031e'>Name</th>" +
"<th class='tg-031e'>Address</th>" +
"<th class='tg-031e'>Work Type</th>" +
"<th class='tg-031e'>Latitude</th>" +
"</tr>" +
"<tr>" +
"<td class='tg-031e'><input type='text' id='name' value='" + name + "'/> </td>" +
"<td class='tg-031e'><input type='text' id='address' value='" + address + "'/> </td>" +
"<td class='tg-031e'><input type='text' id='type' value='" + type + "'/> </td>" +
"<td class='tg-031e'><input type='text' id='lat' value='" + latitude + "'/> </td>" +
"</tr>" +
"</table>" +
"<input type='submit' value='submit' onclick='return chk()'>";
// var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + type + "<br/>" + latitude + "<br/>" + longitude + "<input";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
draggable: true,
icon: icon.icon,
shadow: icon.shadow
});
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() {}
Thanks for the help.
add a dragend listener to your markers.
use that to update the form in the infowindow.
google.maps.event.addListener(marker, 'dragend', function() {
document.getElementById('lat').value = this.getPosition().lat();
document.getElementById('lng').value = this.getPosition().lng();
});
(you probably want to add the longitude to your form as well)
proof of concept fiddle
code snippet:
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
// downloadUrl("phpsqlajax_genxml.php", function (data) {
var xml = parseXml(xmlStr); // data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
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 latlng = markers[i].getPosition();
var latitude = markers[i].getAttribute("lat");
var longitude = markers[i].getAttribute("lng");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
bounds.extend(point);
var html = "<table class='tg'>" +
"<tr>" +
"<th class='tg-031e'>Name</th>" +
"<th class='tg-031e'>Address</th>" +
"<th class='tg-031e'>Work Type</th>" +
"<th class='tg-031e'>Latitude</th>" +
"<th class='tg-031e'>Longitude</th>" +
"</tr>" +
"<tr>" +
"<td class='tg-031e'><input type='text' id='name' value='" + name + "'/> </td>" +
"<td class='tg-031e'><input type='text' id='address' value='" + address + "'/> </td>" +
"<td class='tg-031e'><input type='text' id='type' value='" + type + "'/> </td>" +
"<td class='tg-031e'><input type='text' id='lat' value='" + latitude + "'/> </td>" +
"<td class='tg-031e'><input type='text' id='lng' value='" + longitude + "'/> </td>" +
"</tr>" +
"</table>" +
"<input type='submit' value='submit' onclick='return chk()'>";
// var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + type + "<br/>" + latitude + "<br/>" + longitude + "<input";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
draggable: true,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
// });
map.fitBounds(bounds);
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
google.maps.event.addListener(marker, 'dragend', function() {
document.getElementById('lat').value = this.getPosition().lat();
document.getElementById('lng').value = this.getPosition().lng();
});
}
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() {}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('MicrosoftXMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
google.maps.event.addDomListener(window, 'load', load);
var xmlStr = '<markers><marker name="Mattatuck Trail Parking 1" address="addr1" lat="41.784969" lng="-73.319489" type="parking"/><marker name="Mattatuck Trail Parking 2" address="addr2" lat="41.821751" lng="-73.296867" type="parking"/><marker name="Mattatuck Trail Parking 3" address="addr3" lat="41.784969" lng="-73.319489" type="parking"/><marker name="Mohawk Trail Parking 1" address="addr4" lat="41.818535" lng="-73.368477" type="parking"/><marker name="Mohawk Trail Parking 2" address="addr5" lat="41.784969" lng="-73.319489" type="parking"/><marker name="Appalacian Trail Parking 1" address="addr6" lat="41.731030" lng="-73.490692" type="parking"/><marker name="Appalacian Trail Parking 2" address="addr7" lat="41.807705" lng="-73.391785" type="parking"/><marker name="Appalacian Trail PArking 3" address="addr8" lat="41.731030" lng="-73.490692" type="parking"/><marker name="Dawley Pond Shelter" address="addr9" lat="41.621277" lng="-71.815392" type="shelter"/><marker name="Pachaug Dry Resevoir Shelter" address="addr10" lat="41.590752" lng="-71.881386" type="shelter"/></markers>';
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map" style="border: 2px solid #3872ac;"></div>
Updating draggable markers; through php, to a database. That is your question, right?
Here is a simple example. I disregard anything else, that is not specifically linked to this question.
update.php
<?php
$marerLocations = isset($_POST['markers']) ? $_POST['markers'] : array(); // still a JSON string
$location = json_decode($marerLocations);
echo '<pre>' . print_r($location, true) . '</pre>';
?>
(I presume you can handle the DB update from here on.)
index.php
<div id="map" style="height: 500px;"></div>
<form action="update.php" method="post">
<input readonly="readonly" name="markers" id="markers" style="width: 500px;"><br>
<input type="submit" value="UPDATE">
</form>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var locations = [ // some points in/close to Belgium
[50, 4],
[50.5, 4.5],
[51, 5],
[51.5, 5.5]
];
var markers = [];
function initialize() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(50.5, 4.5),
zoom: 7,
mapTypeId: 'roadmap'
});
// generate the markers
for (var i in locations) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function() {
update_markers();
})
// store the variable in the array
markers.push(marker);
}
update_markers();
function update_markers() {
// read locations of all markers, update var locations
for (var j in locations) {
locations[j] = [markers[j].position.lat(), markers[j].position.lng()]
}
var json_string = JSON.stringify(locations);
document.getElementById("markers").value = json_string;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Javascript shows only last markers

The following code grabs some JSON data from /home.json URL which contain 5 microposts by 6 users. However, only the last 4 markers are shown (not even the 5th !!). I have spend 2 days to find the bug but unfortunately I can't really get why this dosen't work. If anyone could help me I would really appreciate it!
I have tested all lon/Lat variables through alert! All of them have the appropriate data. The map should be ok since the last 4 are shown !! Most probably the problem lies with my closure definition but I really cannot understand what I am doing wrong..
var GMAPS = window.GMAPS || {};
GMAPS.mainMap = function() {
var map;
var infowindow = new google.maps.InfoWindow();
var jsonObject = {};
function addMarkers() {
var xhr = new XMLHttpRequest();
xhr.open( "GET", "/home.json", true );
xhr.onreadystatechange = function () {
if ( xhr.readyState == 4 && xhr.status == 200 ) {
jsonObject = JSON.parse( xhr.responseText );
for (var i=0; i<jsonObject.length; i++) {
for (var j=0; j<jsonObject[i].microposts.length; j++) {
(function(Name, Title, Content, Latitude, Longitude) {
return function() {
//alert(Name + "\n" + Title + "\n" + Content + "\n" + Latitude + "\n" + Longitude + "\n"); //<-- this works!
var position = new google.maps.LatLng(Latitude, Longitude);
var contentString = "<h4>" + Name.bold() + "</h4>" + "<br />" + Title.bold()
+ "<br />" + Content;
var marker = new google.maps.Marker({
position: position,
title: Title,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, contentString) {
return function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
}
})(marker, contentString));
};
})(jsonObject[i].name, jsonObject[i].microposts[j].title,
jsonObject[i].microposts[j].content,
jsonObject[i].microposts[j].lat,
jsonObject[i].microposts[j].lon)();
}
}
}
};
xhr.send(null);
}
function createMap() {
map = new google.maps.Map(document.getElementById('main_map'), {
zoom: 10,
panControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
scrollwheel: false,
center: new google.maps.LatLng(37.975327,23.728701),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function initAddress() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
var position = new google.maps.LatLng(0, 0);
map.setCenter(position);
}
}
function showPosition(position) {
var position = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(position);
}
return {
initMap : function() {
createMap();
initAddress();
addMarkers();
}
};
}();
document.addEventListener("DOMContentLoaded", GMAPS.mainMap.initMap, false);
** Note: you have an unnecessary extra set of parens at the end of your IIFE.
Before your IIFE (inside the innermost for-loop), try adding:
var jObj = jsonObject[i], mPost = jObj.microposts[j];
Then in replace the arguments to the IIFE with:
(function(Name, Title, Content, Latitude, Longitude) {
return function() {
//alert(Name + "\n" + Title + "\n" + Content + "\n" + Latitude + "\n" + Longitude + "\n"); //<-- this works!
var position = new google.maps.LatLng(Latitude, Longitude);
var contentString = "<h4>" + Name.bold() + "</h4>" + "<br />" + Title.bold()
+ "<br />" + Content;
var marker = new google.maps.Marker({
position: position,
title: Title,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, contentString) {
return function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
}
})(marker, contentString));
};
})(jObj.name, mPost.title, mPost.content, mPost.lat, mPost.lon);
The following code should work. I still don't understand why you have the extra set of parentheses.
xhr.onreadystatechange = function() {
var i = 0, j = 0;
if ( xhr.readyState == 4 && xhr.status == 200 ) {
jsonObject = JSON.parse( xhr.responseText );
for (var ilen = jsonObject.length; i < ilen;) {
for (var jObj = jsonObject[i++], jlen = jObj.microposts.length; j < jlen;) {
var mPost = jObj.microposts[j++];
(function(Name, Title, Content, Latitude, Longitude) {
return function() {
//alert(Name + "\n" + Title + "\n" + Content + "\n" + Latitude + "\n" + Longitude + "\n"); //<-- this works!
var position = new google.maps.LatLng(Latitude, Longitude);
var contentString = "<h4>" + Name.bold() + "</h4>" + "<br />" + Title.bold()
+ "<br />" + Content;
var marker = new google.maps.Marker({
position: position,
title: Title,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, contentString) {
return function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
}
})(marker, contentString));
};
})(
jObj.name, mPost.title, mPost.content, mPost.lat, mPost.lon
);
}
}
}
};

Categories