I am building an application that has a database of people's names, info about them and their current location.
I managed to create a maps using Google maps javascript API, and mark your current location. however, i cant seem to be able to use a PHP loop to place a marker with an info window for every person in my database. Here is my code:
lat = position.coords.latitude;
lon = position.coords.longitude;
//init map
myOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var image = 'http://i43.tinypic.com/v48d1w.png';
var loca = new google.maps.LatLng(lat, lon);
var currnetLocationMarker = new google.maps.Marker({
position: loca,
map: map,
animation: google.maps.Animation.DROP,
icon: image
});
var contentString;
var marklatlng;
<?php
require("connect.php");
$query = mysql_query("SELECT * FROM gigs");
$i = 0;
while($data = mysql_fetch_array($query))
{
echo "
contentString = 'Name: <b>" . $data['name'] . "</b><br> Info: <b>" . $data['desc'] . " </b>';
var infowindow" . $i . " = new google.maps.InfoWindow({
content: contentString
});
marklatlng = new google.maps.LatLng(" . $data['lat'] . ", " . $data['lng'] . ");
var marker" . $i . " = new google.maps.Marker({
position: markLatlng,
map: map,
});
google.maps.event.addListener(marker" . $i . ", 'click', function() {
infowindow" . $i . ".open(map,marker" . $i . ");
});
";
$i++;
}
?>
It would be better to json_encode your data, pass that to a variable in javascript, and then loop over it using javascript. Even better would be using AJAX requests to fetch the data.
<?php
function fetchGigs() {
$gigs = new Array();
$query = mysql_query("SELECT * FROM gigs");
while($gig = mysql_fetch_array($query)) {
$gigs[] = $gig;
}
return $gigs;
}
And in your javascript:
<script>
// your other code...
var gigs = <?php echo json_encode(fetchGigs()); ?>
var createMarkerAt = function(lat, lng) {
var latLng, marker;
latLng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latLng,
map: map,
});
return marker;
}
var createMarkerForGig = function (gig) {
var marker, info;
marker = createMarkerAt(gig.lat, gig.lng);
info = new google.maps.InfoWindow({
content: 'Name: <b>"' + gig.name + '"</b><br>Info: <b>"' + gig.desc + '"</b>'
});
google.maps.event.addListener(marker, 'click', function() {
info.open(map, marker);
});
return marker;
}
// Add markers for all the gigs.
var len = gigs.length;
for (var i = 0; i<len; i++) {
createMarkerForGig(gigs[i]);
}
</script>
Documentation for php_encode()
When I wrote a similar application I used php to write the string of a javascript array representing my data and then used straight js once i got to building strings for the api. However, since I have discovered how easy it is to write a PHP powered API to return JSON objects of my database I just use jQuery to query my homebrew API for the json data and then work with that. It truly is incredibly easy to do with SLIM. Here is a link http://codingthis.com/programming/php/using-the-slim-php-framework-for-developing-rest-apis/
Related
i am new to stack overflow.please edit my question if it looks wrong.
i have div tag with id="map" that contain google map i want to refresh that div at every 1 min.
<div id="map" style="width: 100%; height: 500px"></div>
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng("<?php echo $lat;?>", "<?php echo $lng;?>"),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("mapajax.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 email = markers[i].getAttribute("email");
var phone = markers[i].getAttribute("phone");
var status = markers[i].getAttribute("status");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + email+ "</b> <br/>" + phone+ "</b> <br/>" + status;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
you can use setinterval for every sec. refresh like below , off course you can edit the function according to your need like 1 sec = 1000 ms,
you can use 60000 for 1 min
setInterval(function(){
load()
}, 60000);
I am looping through some JSON files and using the address from the JSON file for the google maps. I know the address is working properly because I set an alert to show the variable and it's showing what I expect. The call for the map is inside a click function. on one virtual page I have a list of customers and when the user clicks that customer, it redirects to another virtual page to display that customers information, with a map showing their address. When I do this for the first time , it works. If I click back, then select a different customer the map is just grey. Any idea why this is happening?
Here is my click function..
function cHandle(num) {
$("#custSpan" + i).on("click", function () {
window.location.href = "#CustInv";
custName = customer.Customer[num].compName;
$("#CustInvHead").html(custName);
$("#invoiceh2").html(custName + "'s Invoices");
$("#custInfo").empty();
$("#invoice").empty();
$("#map-canvas").empty();
var inc = customer.Customer[num].compId;
$("#custInfo").append("Customer ID: " + customer.Customer[num].compId + "<br /><br />"
+"Customer Name: " + custName + "<br /><br />"
+"Customer Address: " + customer.Customer[num].compAddress + "<br /><br />"
+"Customer Contact: " + customer.Customer[num].compContact + "<br /><br />"
+"Customer Phone: " + customer.Customer[num].compPhone + "<br/ ><br />"
+ "Customer Email: " + customer.Customer[num].compEmail + ""
);
address = customer.Customer[num].compAddress;
//alert(address);
codeAddress();
})
}
cHandle(i);
And here is my maps stuff..
function success(pos) {
lat = pos.coords.latitude;
lng = pos.coords.longitude;
drawMap();
}
function error(err) {
alert("Error " + err.code + " : " + err.message);
}
;
function codeAddress() {
lat = 0;
lng = 0;
//Get the address
//address = "123 Fake St";
if (address == "") {
alert("No Address Entered");
return;
}
//Change address to coordinates to plot on map
else {
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myLatLng = results[0].geometry.location;
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
drawMap();
}
else {
alert("Geocode was not successful for the following reason: " + status);
return;
}
})
}
}
function drawMap() {
mapCenter = new google.maps.LatLng(lat, lng);
var mapOptions = {
center: mapCenter,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Display the address
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
//Map Marker
var myLoc = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: mapCenter
});
You call several times the creation of the map as you should call once (Initialize) map and call several times the function of creating the marker.
split the code in drawMap in two
first declare the var map at top (window) level (outside the functions)
and initialize your map
var map
function initialize() {
mapCenter = new google.maps.LatLng(lat, lng);
var mapOptions = {
center: mapCenter,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Display the address
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addDomListener(window, 'load', initialize);
</script>
second in the codeAddress() function call only the create marker function
function createMarker() {
var myLoc = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: mapCenter
});
}
I've a problem with pushing array html content into an infowindow:
I whant to try to append a html string for each marker that i customize via javascript into the Map, the code work with a native infowindow, but when i try to append html the infowindow is empty.
Here the code:
function initialize(markerPlaces) {
(function(window, google, maplib){
var mapOptions = maplib.MAP_OPTIONS,
domElement = document.getElementById('map'),
//map declaration
map = new google.maps.Map(domElement, mapOptions);
console.log(markerPlaces);
var contentStringOpen = '<div class="modul1 modalWindow">';
var contentStringMiddle = '<span class="modul1_txt">';
var contentStringClose = '</span></div>';
var infowindow = new google.maps.InfoWindow();
var contArray = new Array();
for(i=0;i<markerPlaces[0].posts.length;i++){
var thumb = markerPlaces[0].posts[i].thumb;
var title = markerPlaces[0].posts[i].title;
contArray.push('' +
'<div id="' + markerPlaces[0].posts[i].postId +
'" class="modul1 modalWindow">' +
markerPlaces[0].posts[i].thumb +
'<span class="modul1_txt">' +
markerPlaces[0].posts[i].title +
'</span></div>');
markers = new google.maps.Marker({
position: {
lat: Number(markerPlaces[0].posts[i].lat),
lng: Number(markerPlaces[0].posts[i].long)
},
map: map,
icon: 'http://tovisit.today/wp-content/themes/turisti/img/poi.png',
title: markerPlaces[0].posts[i].title
})
console.log(contArray[i]);
google.maps.event.addListener(markers, 'click', (function(markers, i) {
return function() {
//switch this for htmlContent
//infowindow.setContent(contArray[i]);
//this work
infowindow.setContent(contentStringMiddle + markerPlaces[0].posts[i].title + contentStringClose + markerPlaces[0].posts[i].thumb);
infowindow.open(map, markers);
$()
}
})(markers, i));
}
}(window, google, window.maplib || (window.maplib = {})));
}
The content string is correct:
but when i ispect the dom the div.modalWindow, and his content, missing
anyone has the same trouble?
i solve the problem, sometime a display:none cause some trouble, i forgot this debug css line, i apologize for loosinrg your time.
The function is correct and work by the way.
Thank U for the -1 have a nice day
Hi, I'm trying to make a website with Google Maps API and get coords from MySQL db. So far so good, but only in Chrome or Safari. Markers won't show in Internet Explorer. I could use some help. I followed this guide from Google https://developers.google.com/maps/articles/phpsqlajax_v3
Anyway, here's my code. Any help would be appreciated, thanks.
var customIcons = {
sport: {
icon: 'images/markers/sport.png',
},
bar: {
icon: 'images/markers/bar.png',
},
poi: {
icon: 'images/markers/poi.png',
},
skola: {
icon: 'images/markers/skola.png',
},
kino: {
icon: 'images/markers/kino.png',
},
divadlo: {
icon: 'images/markers/divadlo.png',
}
};
function nactimapu() {
var map = new google.maps.Map(document.getElementById("mapa"), {
center: new google.maps.LatLng(49.068299, 17.460907),
zoom: 15,
mapTypeId: 'hybrid'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("querymapa.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var nazev = markers[i].getAttribute("nazev");
var popis = markers[i].getAttribute("popis");
var typ = markers[i].getAttribute("typ");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + nazev + "</b> <br/>" + popis;
var icon = customIcons[typ] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
animation: google.maps.Animation.DROP,
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() {}
Here is xml output in php, maybe there is a mistake. Sorry that I didn't post it earlier.
<?php
require("dbconfig.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect ($dbserver, $dbuser, $dbheslo);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($dbname, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM lokace WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'nazev="' . parseToXML($row['nazev']) . '" ';
echo 'popis="' . parseToXML($row['popis']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'typ="' . $row['typ'] . '" ';
echo '/>';
// End XML file
echo '</markers>';
?>
You have extra commas in your arrays:
sport: {
icon: 'images/markers/sport.png', <-- Right here (among other places)
}
Internet Explorer doesn't like that, while other browsers don't mind them. You can safely remove them.
sport: {icon: 'images/markers/sport.png',},
Explorer expects (other browsers ignore this) that you add another command to this, such as latitude - or longitude coordinates and other items specified in your marker. Remove the comma before the closing bracket and you should be fine
as example, i posted below here a marker from my own work, so you can see, when i close the bracket, i dont use a comma anymore
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: yay,
title: title,
icon: icon
});
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.