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
});
Related
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);
});
});
}
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>
Good Day, I just wanna ask something about markers.
1. I have a folder consist of 3 gif's and that is fire,carnapping and homicide
2.I also have a database,a table and inside of that I have a field name "icon_name" with other fields 3. This is my image folder location C:\wamp\www\wew\legends
Here is my code:
function getInfo() {
$.getJSON("get_info.php", function (data) {
for (var i = 0; i < data.length; i++) {
var location = new L.LatLng(data[i].lat, data[i].lng);
var marker = new L.Marker(location,{iconUrl: 'C:\wamp\www\New System CS\SanBartolome\wew\legends' + data[i].icon_name + '.gif'});
marker.bindPopup(
data[i].name + "<br>" +
data[i].user_date + "<br>" +
data[i].user_time + "<br>" +
data[i].address + "<br>"
).addTo(map);
marker.on('click', function(e) { // HERE YOU GO
var ll = marker.getLatLng();
document.querySelector('#userLat1').value = ll.lat;
document.querySelector('#userLng1').value = ll.lng;
alert('You have selected a Marker that will be deleted');
});
}
});
}
Here is the get_info.php
<?php
$db = new PDO('mysql:host=localhost;dbname=poi', 'root', '');
$sql = "SELECT name,user_date,user_time,address,lat,lng,icon_name FROM tblmarker";
$rs = $db->query($sql);
if (!$rs) {
echo "An SQL error occured.\n";
exit;
}
$rows = array();
while($r = $rs->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $r;
$name[] = $r['name'];
$user_date[] = $r['user_date'];
$user_time[] = $r['user_time'];
$address[] = $r['address'];
$icon_name[] = $r['icon_name'];
}
print json_encode($rows);
$db = NULL;
?>
This is what it does:
1.call my get_info.php which consist of a code of select * from tablename
2.var location: get the value of lat and long in database
3.creating the marker (default marker)
4. get the data from database and transfer it in leaflet bindpop up
and the result is a default marker in a map that has been generated using the data from database.
This is my question: How can I pass the data inside my table field "icon_name" into the markers image? I mean use the icon_name data's to call the image in a folder and use it as a marker.
TYIA
Try this. Use your own icons folder path.
function getInfo() {
$.getJSON("get_info.php", function (data) {
for (var i = 0; i < data.length; i++) {
var location = new L.LatLng(data[i].lat, data[i].lng);
var marker = new L.Marker(location,{icon: '/path/to/icons/' + data[i].icon_name});
marker.bindPopup(
data[i].name + "<br>" +
data[i].user_date + "<br>" +
data[i].user_time + "<br>" +
data[i].address + "<br>"
).addTo(map);
marker.on('click', function(e) { // HERE YOU GO
var ll = marker.getLatLng();
document.querySelector('#userLat1').value = ll.lat;
document.querySelector('#userLng1').value = ll.lng;
alert('You have selected a Marker that will be deleted');
});
}
});
}
Add + '.gif' after icon_name if icon_name doesn't include the file extension.
I'm sorry if there is another similar post, but it is hard to formalize a question with my problem. So I have a page with Google maps and two forms which can add points on map with extra information. One form working very well, another not so well. My language is lithuanian, so I have some special characters like 'ąčęėįšųū', and with second form after submit I have bad values in database like '%u0117%u0161'.
In the image Number 1., this form working well. Number 2. is the form which makes encoding problems, and Number 3. is the result after submit form number 2.
For the second form I used Google tutorial (https://developers.google.com/maps/articles/phpsqlinfo_v3), and edited some small things.
So I would be grateful if someone will help me to solve this.
Javascript code:
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: 0,
center: new google.maps.LatLng(55.203953, 24.873047),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
panControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
var html = "<table>" +
"<tr><td>Pavadinimas:</td> <td><input type='text' name='name' id='name'/> </td> </tr>" +
"<tr><td>Miestas:</td> <td><input type='text' name='city' id='city'/></td> </tr>" +
"<tr><td>Adresas:</td> <td><input type='text' name='adress' id='adress'/></td> </tr>" +
"<tr><td>Apibudinimas:</td> <td><input type='text' name='description' id='description'/></td> </tr>" +
"<tr><td>Type:</td> <td><select id='type'>" +
"<option value='Baras' SELECTED>Baras</option>" +
"<option value='Restoranas'>Restoranas</option>" +
"<option value='Degalinė'>Degalinė</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
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
center = bounds.getCenter();
map.fitBounds(bounds);
}
function saveData() {
var name = escape(document.getElementById("name").value);
var adress = escape(document.getElementById("adress").value);
var city = escape(document.getElementById("city").value);
var description = escape(document.getElementById("description").value);
var type = document.getElementById("type").value;
var latlng = marker.getPosition();
var url = "phpsqlinfo_addrow.php?name=" + name + "&adress=" + adress + "&city=" + city +
"&description=" + description + "&type=" + type + "&lat=" + latlng.lat() + "&lon=" + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
document.getElementById("message").innerHTML = "Location added.";
}
});
$(document).ready(function() {
setTimeout("ReloadPage()", 100);
});
}
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 ReloadPage() {
location.reload();
};
function doNothing() {}
PHP insert code:
require("controller/phpsqlinfo_dbinfo.php");
// Gets data from URL parameters
$name = $_GET['name'];
$adress = $_GET['adress'];
$city = $_GET['city'];
$description = $_GET['description'];
$lat = $_GET['lat'];
$lon = $_GET['lon'];
$type = $_GET['type'];
// Opens a connection to a MySQL server
$connection=mysql_connect ("localhost", $dbuser, $dbpass);
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());
}
// Insert new row with user data
//$submit="INSERT INTO poi_example (id, name, city, adress, description, lat, lon, type) VALUES (NULL,'$name','$city', '$adress','$description','$lat','$lon','$type');";
$query = sprintf("INSERT INTO poi_example " .
" (id, name, adress, city, description, lat, lon, type ) " .
" VALUES (NULL, '%s', '%s', '%s', '%s', '%s', '%s', '%s');",
mysql_real_escape_string($name),
mysql_real_escape_string($adress),
mysql_real_escape_string($city),
mysql_real_escape_string($description),
mysql_real_escape_string($lat),
mysql_real_escape_string($lon),
mysql_real_escape_string($type));
$result = mysql_query($query);
//print_r($result);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Is it possible that your (local?) database is not configured to use the right encoding? I think UTF-8 for example may be better suited for lithuanian. I think the standard encoding of MySQL ist somthing like latin1? It's just a guess, but you may have to check that.
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/