Below is code initially Google maps API for saving user defined data into DB, but i tweaked it to load form in users location marker. and now the save function doesn't help. please help
Register as a Money lender.
Cell:
Business name:
Collateral: +
Laptops,Phones,TVs.
Salary Backed Loan
Open for Negotiation
Amountavailable: +
Less than K3000
More than K3000
<div id="message">You have been registered as a money lender at this location.</div>
<script>
var map;
var marker;
var infowindow;
var messagewindow;
function initMap() {
var zambia = {lat: -15.376085, lng: 28.366237};
map = new google.maps.Map(document.getElementById('map'), {
center: zambia,
zoom: 7
});
var infoWindow = new google.maps.InfoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent(document.getElementById('form'));
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'We cant seem to find you my friend.' :
'Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
function saveData() {
var name = escape(document.getElementById('name').value);
var address = escape(document.getElementById('address').value);
var collateral = document.getElementById('collateral').value;
var type = document.getElementById('type').value;
var latlng = getCurrentPosition(pos);
var url = 'phpsqlinfo_addrow.php?name=' + name + '&address=' + address + '&collateral=' + collateral +
'&type=' + type + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
messagewindow.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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing () {
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
I tried to replicate your exact issue but I failed. So what I did is to revise your code a bit so I can further investigate.
Upon my investigation, there are some lines of your code that seems will likely won't work.
Like this line: infoWindow.setContent(document.getElementById('form'));. I believe this line won't work the way you expect it. What I would rather suggest is, to create a js variable that contains html tag - form elements to be exact and the set this as content of your Google Maps Javascript API InfoWindow.
You can check to code below to see what I am talking about:
var template = '<form>';
template += '<input id="name" type="text" placeholder="name" /><br/>';
template += '<input id="address" type="text" placeholder="address" /><br/>';
template += '<input id="collateral" type="text" placeholder="collateral" /><br/>';
template += '<input id="type" type="text" placeholder="type" /><br/>';
template += '<button onclick="saveData('+position.coords.latitude+','+position.coords.longitude+');">Add my location</button>';
template += '</form>';
infoWindow.setContent(template);
You will also notice that I've attached the 'saveData()' function as an onclick event in button that we created.
I've also revised your saveData() function. As you can see, it accepts two arguments: lat and lng. These arguments will replace your latlng that contains an undefined getCurrentPosition() function. If you are referring to HTML5 Geolocation getCurrentPosition method, I am afraid that is not the correct way to implement it.
Here's what the new saveData() function looks like:
function saveData(lat,lng) {
var pos = {
lat : lat,
lng : lng
}
var name = escape(document.getElementById('name').value);
var address = escape(document.getElementById('address').value);
var collateral = document.getElementById('collateral').value;
var type = document.getElementById('type').value;
var url = 'phpsqlinfo_addrow.php?name=' + name + '&address=' + address + '&collateral=' + collateral +
'&type=' + type + '&lat=' + pos.lat + '&lng=' + pos.lng;
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
messagewindow.open(map, marker);
}
});
//console.log(url);
}
Checking From Info Windows to a Database: Saving User-Added Form Data would be very helpful in your use case.
Hope my answer could help and happy coding!
Related
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)
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>
For now, on a button click I have it so that it takes in data from two textboxes, and uses it to
1) append tweets to a panel, and
2) drop pins on a map.
My next step is to have it so that on the button click, it geodecodes a location, and does the same thing. I feel like my jquery.click function is getting really big, and wanted to know if there was a standard way to "separate" it out to make it look prettier and more readable. Can you typically have javascript functions within a jquery file that are called upon, or what is the way to go?
Here is my current jquery file. As you can see it's very big but what happens is straight forward: searchbutton on click takes some values, and sets up a new map in that location, then I access my web server's information, append it to a panel, and also drop pins on a map.
$(function () {
$("#search-button").click(function() {
// variables for google maps
var LatValue = parseFloat($("#searchLat").val());
var LonValue = parseFloat($("#searchLon").val());
var myLatLng = {lat: LatValue, lng: LonValue};
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: myLatLng
});
$.getJSON(
"http://localhost:3000/tw",
{
geoSearchWord: $("#searchme").val(),
geoSearchWordLat: $("#searchLat").val(),
geoSearchWordLon: $("#searchLon").val(),
geoSearchWordRad: $("#searchRadius").val()
}
).done(function (result) {
$("#fromTweets").empty();
console.log(result);
for (i = 0; i < result.statuses.length; i++) {
//Print out username and status
$("#fromTweets").append('<b>' + "Username: " + '</b>' + result.statuses[i].user.screen_name + '<br/>');
$("#fromTweets").append('<b>' + "Tweet: " + '</b>' + result.statuses[i].text + '<br/>');
$("#fromTweets").append('<b>' + "Created at: " + '</b>' + result.statuses[i].created_at + '<br/>');
if (result.statuses[i].geo !== null) {
//Print out the geolocation
$("#fromTweets").append('<b>' + "GeoLocation: " + '</b>' + "Lat: " + result.statuses[i].geo.coordinates[0] + " Lon: " + result.statuses[i].geo.coordinates[1] + '<br/>'+ '<br/>');
//dropping a new marker on the map for each tweet that has lat/lon values
//Multiplying by i * 0.0005 to space them out in case they are from the same gelocation while still holding
//the integrity of their location.
LatValue = parseFloat(result.statuses[i].geo.coordinates[0] + i*0.0005);
LonValue = parseFloat(result.statuses[i].geo.coordinates[1] + i*0.0005);
myLatLng = {lat: LatValue, lng: LonValue};
var newMarker = new google.maps.Marker({
position: myLatLng,
map: map,
animation: google.maps.Animation.DROP,
});
} else {
$("#fromTweets").append('<b>' + "GeoLocation: " + '</b>' + "Cannot be identified" + '<br/>' + '<br/>')
}
}
});
});
The most simple and obvious thing you can do it so split your code by extracting independent logical blocks to functions:
Just something like this:
var map;
function combineTweetsAjaxRequestData()
{
return {
geoSearchWord: $("#searchme").val(),
geoSearchWordLat: $("#searchLat").val(),
geoSearchWordLon: $("#searchLon").val(),
geoSearchWordRad: $("#searchRadius").val()
};
}
function createGMap()
{
return new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: {
lat: parseFloat($("#searchLat").val()),
lng: parseFloat($("#searchLon").val())
}
});
}
function createGMarker(coords)
{
var coordsFixed = {
lat: parseFloat(coords[0] + i * 0.0005),
lng: parseFloat(coords[1] + i * 0.0005)
};
return new google.maps.Marker({
position: coordsFixed,
map: map,
animation: google.maps.Animation.DROP,
});
}
function clearInfo() {
$("#fromTweets").empty();
}
function appendInfo(title, text)
{
$("#fromTweets").append('<b>' + title + ':</b> ' + text + '<br/>');
}
function processTweet(tw)
{
appendInfo('Username', tw.user.screen_name);
appendInfo('Tweet', tw.text);
appendInfo('Created at', tw.created_at);
if (tw.geo !== null) {
var twCoords = tw.geo.coordinates;
appendInfo('GeoLocation', "Lat: " + twCoords[0] + " Lon: " + twCoords[1]);
createGMarker(twCoords);
} else {
appendInfo('GeoLocation', "Cannot be identified")
}
}
function loadTweets() {
$.getJSON(
"http://localhost:3000/tw",
combineTweetsAjaxRequestData()
).done(function (result) {
clearInfo();
console.log(result);
result.statuses.forEach(processTweet);
});
}
$(document).ready(function () {
map = createGMap();
$("#search-button").click(function() {
loadTweets();
});
});
Now, it can be easily read as a text. Your code should be readable and understandable from the first glance. Even better, if a non-developer can read it and understand some basic concepts.
What happens when the page is loaded? We create a Google map control and load tweets
How do we load tweets? We make a AJAX request by combining request data from inputs
What happens when it is loaded? We clear out current information and process every tweet
How do we process a single tweet? We output some basic information. Then, we output geolocation if it is available. Otherwise, we output an error.
Now, if you need to add information to another source, you won't extend or modify your loadTweets method - you will extend or modify appendInfo method, because the logics of information output is encapsulated here.
I am wanting to search a KML file to see if a particular address falls within an overlay. Presently, I have the address converting to a geocode. However, I'm not sure what code is needed to add this functionality.
Here's the present code:
function initialize() {
var infowindow = new google.maps.InfoWindow({
content: '',
suppressMapPan:true
});
var myLatlng = new google.maps.LatLng(35.910200,-84.085100);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map_canvas"), myOptions);
var d = new Date();
var n = d.getMilliseconds();
var nyLayer = new google.maps.KmlLayer(
'http://www.cspc.net/neighborhoods/groups.kml?rand=' + n,
{ suppressInfoWindows: true, map: map});
google.maps.event.addListener(nyLayer, 'click', function(kmlEvent) {
var url = kmlEvent.featureData.snippet;
var groupName = kmlEvent.featureData.name;
var insideContent = "<div style='width:250px;'><h2>" + groupName +
"</h1><p>We have a neighborhood contact in your area! </p>" +
"<p><a href='" + url + "' target='_blank'>Get connected!</a>" +
" They look forward to hearing from you.</p><p>If you have " +
"any additional questions, please contact our " +
"<a href='http://www.cspc.net/communitylife' target='_blank'>" +
"Community Life</a> staff for more information. Betsy Palk, " +
"the Administrative Assistant, may be reached at:<br/><br/>" +
"<b>Email:</b> <a href='mailto:betsypalk#cspc.net'>" +
"betsypalk#cspc.net</a><br/><b>Phone:</b> 865-291-5268<p></div>";
var clickPos = kmlEvent.latLng;
var posX = new google.maps.LatLng(clickPos.lat(), clickPos.lng());
infowindow.close();
infowindow.setPosition(posX);
infowindow.setContent(insideContent);
infowindow.open(map);
});
eventMapClick = google.maps.event.addListener(map, 'click',
function(event) {
var marker = new google.maps.Marker({ position: event.latLng });
var outsideContent = "<div style='width:250px;'><h2>Oops!</h1>" +
"<p> It seems we don't have a neighborhood contact in your " +
"area.</p><p>Please contact our <a " +
"href='http://www.cspc.net/communitylife' target= '_blank'>" +
"Community Life</a> staff for more information. " +
"Betsy Palk, the Administrative Assistant, may be reached at:" +
"<br/><br/><b>Email: </b> <a href='mailto:betsypalk#cspc.net'>" +
"betsypalk#cspc.net</a><br/><b>Phone:</b> 865-291-5268<p></div>";
infowindow.setContent(outsideContent);
infowindow.open(map, marker);
});
}
var geocoder = new google.maps.Geocoder();
function searchAddress(address) {
geocoder.geocode(
{'address': address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var loc = results[0].geometry.location;
// use loc.lat(), loc.lng()
window.alert(loc);
}
else {
window.alert("Not found: " + status);
}
}
);
};
If I understand your question, I believe you want the formula to determine if a point (google.maps.LatLng) falls within one of your KML Placemark definitions (that you give names such as: Neighborhood Group 1). Within each Placemark, you define a Polygon and within each Polygon, you define a set of coordinates, which represent the vertices of the Polygon.
Using the coordinates within the Polygon and the LatLng you retrieve via geocoding, you could start with these formulas and select that one that is the best fit for you:
Fast Winding Number Inclusion of a Point in a Polygon
Point-In-Polygon Algorithm
A very similar question has also been asked here on SO: Determine the lat lngs of markers within a polygon.
and I know that 1-801-555-1212 will make this certain number be clickable. I tested it and it works fine.
My question is if I do have a variable phone which will call from database via mysql, how can I make this variable be clickable? I've tried a lot of way but none of them work.
I used the following link to create a store locator page
http://code.google.com/apis/maps/articles/phpsqlsearch.html
and my original code is here.
<!DOCTYPE html>
Store Locate
<script src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAAtwc3xGzBndDAUOSllG2AkxTnNPa_SyQGEldLwhmK8Cfx_H4lPRTZuzWKU2EDVO1MyUD3Ym_0fNuEiw" type="text/javascript"></script>
<script src="jquery-1.5.2.min.js"></script>
<script>
// One-shot position request.
navigator.geolocation.getCurrentPosition(showMap);
function showMap(position) {
// Show a map centered at (position.coords.latitude, position.coords.longitude).
}
map.setCenter(new google.maps.LatLng(position.coords.latitude,
position.coords.longitude), 13);
<script type="text/javascript">
//<![CDATA[
var map;
var geocoder;
function load() {
if (GBrowserIsCompatible()) {
geocoder = new GClientGeocoder();
map = new GMap2(document.getElementById('map'));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(40, -100), 4);
}
}
function searchLocations() {
var address = document.getElementById('addressInput').value;
geocoder.getLatLng(address, function(latlng) {
if (!latlng) {
alert(address + ' not found');
} else {
searchLocationsNear(latlng);
}
});
}
function searchLocationsNear(center) {
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
GDownloadUrl(searchUrl, function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
if (markers.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new GLatLng(40, -100), 4);
return;
}
var bounds = new GLatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var distance = parseFloat(markers[i].getAttribute('distance'));
var phone = markers[i].getAttribute('phone');
var url = markers[i].getAttribute('url');
var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
parseFloat(markers[i].getAttribute('lng')));
var marker = createMarker(point, name, address, phone, url);
map.addOverlay(marker);
var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone, url);
sidebar.appendChild(sidebarEntry);
bounds.extend(point);
}
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
});
}
function createMarker(point, name, address, phone, url) {
var marker = new GMarker(point);
var html = '<b>' + name + '</b> <br/>' + address + '</b> <br/>' + phone + '</b> <br/>' + url + '</b> <br/>'
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
function createSidebarEntry(marker, name, address, distance, phone, url) {
var div = document.createElement('div');
var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address + '</b> <br/>' + phone + '</b> <br/>' + url;
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
GEvent.addDomListener(div, 'click', function() {
GEvent.trigger(marker, 'click');
});
GEvent.addDomListener(div, 'mouseover', function() {
div.style.backgroundColor = '#eee';
});
GEvent.addDomListener(div, 'mouseout', function() {
div.style.backgroundColor = '#fff';
});
return div;
}
//]]>
</script>
I add a variable phone which will call from mysql. and my question is how can I make it clickable?...I tried to modify following code in many ways
function createSidebarEntry(marker, name, address, distance, phone, url) {
var div = document.createElement('div');
var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address + '</b> <br/>' + phone + '</b> <br/>' + url;
but I always just got code error.
anyone can help me??
thanks
You can surround the phone number by a "a" tag with a href="tel:{PHONE NUMBER}"
How to mark-up phone numbers?