Setting location markers for each location on google map - javascript

I have code that I'm using (I didn't write it myself) that creates a Polyline on top of a google map based on lon and lat entries I have in my DB. It's working well right now. I'd like to add a marker for each location that makes up the line on the map so I can click on it and see the time, lon and lat info from the DB record for that point.
Here is the current code:
<?php
function flightpath($days = 1) {
if (($days > 100) || ($days < 1) || (!is_numeric($days))) {
echo 'Please specify a correct number of days (maximum 100 days)';
return;
}
$flightpath_part[0] = "<script>
function initialize() {
var myLatLng = new google.maps.LatLng(";
$flightpath_part[1] = ");
var mapOptions = {
zoom: 11,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var flightPlanCoordinates = [
";
$flightpath_part[2] = "
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 3
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo 'Connection with MySQL database failed!';
exit();
}
$query = "SELECT `log`, `lat`, `lon` FROM `location` WHERE `log` >= ( DATE_SUB( CURDATE( ), INTERVAL " . ($days -1) . " DAY ) ) AND user_id = '$user_idA' ORDER BY `log` ASC";
$result = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($result);
if ($rowcount == 0) {
echo "<br /><br /><br /><center><p>You have no locations in your database for this period!</p></center>";
} else {
$lat_sum = 0;
$lon_sum = 0;
$loc_sum = 0;
$flightpath = '';
while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
foreach ($line as $col_value) {
$lon = $line['lon'];
$lat = $line['lat'];
$lon_sum = $lon_sum + $lon;
$lat_sum = $lat_sum + $lat;
$loc_sum = $loc_sum + 1;
if ($lon && $lat) {
$flightpath .= " new google.maps.LatLng(";
$flightpath .= $line['lat'];
$flightpath .= ", ";
$flightpath .= $line['lon'];
$flightpath .= "),\r\n";
}
}
}
$lon_center = $lon_sum / $loc_sum;
$lat_center = $lat_sum / $loc_sum;
$flightpath = substr_replace($flightpath, "", -3);
$flightpath = $flightpath_part[0] . $lat_center . ', ' . $lon_center . $flightpath_part[1] . $flightpath . $flightpath_part[2];
}
mysqli_close($conn);
return $flightpath;
}
?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=visualization"></script>
<?php echo flightpath($days); ?>

Since the database has the lon and lat coordinates stored you can use those to create the map markers. You could try something like:
function flightmarkers($days=1){
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo 'Connection with MySQL database failed!';
exit();
}
$query = "SELECT `log`, `lat`, `lon` FROM `location` WHERE `log` >= ( DATE_SUB( CURDATE( ), INTERVAL " . ($days -1) . " DAY ) ) AND user_id = '$user_idA' ORDER BY `log` ASC";
$result = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($result);
if ($rowcount == 0) {
echo "<br /><br /><br /><center><p>You have no locations in your database for this period!</p></center>";
} else {
$flightmarkers= '';
while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
foreach ($line as $col_value) {
$lon = $line['lon'];
$lat = $line['lat'];
if ($lon && $lat) {
$flightmarkers.=
'marker = new google.maps.Marker({
position: new google.maps.LatLng('.$line['lat'].','.$line['lon'].'),
map: map
});
';
}
}
return $flightmarkers;
}
<?php echo flightpath($days); ?>
<?php echo flightmarkers($days); ?>
I can't test it and I wasn't sure of the point of *_sum vars considering they are statically set to 0 so they dont really do anything. I removed them for simplicity. This might at least get you started in the right direction.
This link has a good bit of info about map markers also Google Maps JS API v3 - Simple Multiple Marker Example

Related

Transfer json array from PHP to JS

I am trying to transfer a json array from PHP to JS
<?php
//controllo se sono presenti i parametri
if(isset($_GET['id_utente']) && isset($_GET['longitude']) && isset($_GET['latitude']))
{
//Recupero il valore dei parametri
$id_utente = $_GET['id_utente'];
$longitude= $_GET['longitude'];
$latitude = $_GET['latitude'];
}
$servername = "localhost";
$username = "realegr";
$password = "pass";
$dbname = "my_realegr";
// Create connection,
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully\n";
// Insert Data
$sql = "INSERT INTO Prova (id_utente, latitude, longitude)
VALUES ('" . $id_utente . "', '" . $longitude . "', '" . $latitude . "')
";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully\n\r";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Execute query and save it in result
$sql = "SELECT latitude,longitude FROM Prova ORDER by reg_date DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
//if (mysqli_num_rows($result) > 0) {
// output data of each row
/* while($row = mysqli_fetch_assoc($result)) {
echo "latitude: " . $row["longitude"]. " - longitude: " . $row["latitude"]. "<br>";
}
} else {
echo "0 results";
}
*/
$row = mysqli_fetch_assoc($result);
echo json_encode([
'status' => true,
'latitude' => $row["longitude"],
'longitude' => $row["latitude"],
]);
mysqli_close($conn);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBkEtPH07_xBVh8dWBzCQYtWimkOUnPGMQ&callback=initMap"></script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap(){
var $request = $.get('http://realegr.altervista.org/PopolamentoTabella.php');
$request.done( function(data) {
alert(data);
var pasedData = JSON.parse(data);
var longi = parseFloat(pasedData.longitude);
var lati = parseFloat(pasedData.latitude);
var uluru = {lat: lati, lng: longi};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
})
}
</script>
</body>
</html>
The php script seems work well.It updates the DB and echo the JSON array,as it should.
But when I try to load the Maps it gives me some error:
Beside in console I have this:
further information:evry time I send data to DB( with a get request), the php script has to send (only)gps coordinates to JS,to show them on a google maps
Change your 'PopolamentoTabella.php' to this
<?php
$servername = "localhost";
$username = "YOURUSERNAME";
$password = "YOURPASSWORD";
$dbname = "YOUR DB";
// Create connection,
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully\n";
//controllo se sono presenti i parametri
if (isset($_GET['id_utente']) && isset($_GET['longitude']) && isset($_GET['latitude'])) {
//Recupero il valore dei parametri
$id_utente = $_GET['id_utente'];
$longitude = $_GET['longitude'];
$latitude = $_GET['latitude'];
// Insert Data
$sql = "INSERT INTO Prova (id_utente, latitude, longitude)
VALUES ('" . $id_utente . "', '" . $longitude . "', '" . $latitude . "')
";
if (mysqli_query($conn, $sql)) {
//echo "New record created successfully\n\r";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
} else {
// Execute query and save it in result
$sql = "SELECT latitude,longitude FROM Prova ORDER by reg_date DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
//if (mysqli_num_rows($result) > 0) {
// output data of each row
/* while($row = mysqli_fetch_assoc($result)) {
echo "latitude: " . $row["longitude"]. " - longitude: " . $row["latitude"]. "<br>";
}
} else {
echo "0 results";
}
*/
$row = mysqli_fetch_assoc($result);
echo json_encode([
'status' => true,
'latitude' => $row["longitude"],
'longitude' => $row["latitude"],
]);
}
//echo $longitude;
mysqli_close($conn);
?>

Having divs act as button objects to retrieve data

I populated a list using the following code.
I'm trying to make each of the objects retrieved from the server act like a button and when clicked throw a pop up box displaying address, date, and status. Is there anyway to do this? I've been looking into using Ajax but it is getting a little confusing as I have an html file and a php file that has all my javascript/php (the javascript relies on a php function) and from what I've read I would need to make another php file to service the request. How then would I reference it within my html file to do so? I may be making this harder than it needs to be.
Original Code:
<?php
function getjson(){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, lng, lat FROM information WHERE username = '" . $_SESSION['user_name'] . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
switch($row["status"]){
case 3:
echo '<div id= "content" style = "background-color: red" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
case 4:
echo '<div id= "content" style = "background-color: yellow" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
case 5:
echo '<div id= "content" style = "background-color: green" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
}
}
}
$db_connection->close();
}
function getalerts($id){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE id = '" . $id . "';";
$result = $db_connection->query($sql);
$temp = array();
$row = $result->fetch_assoc();
$temp[] = $row;
$db_connection->close();
return json_encode($temp);
}
?>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script>
function getlocations(){
var data = <?php echo getjson(); ?>;
var i = 0;
var locations = new Array();
for(i; i < data.length; i++){
var dataholder = [data[i].misc, parseFloat(data[i].lat), parseFloat(data[i].lng)];
locations.push(dataholder);
}
return locations;
}
function createmap(){
var locations = getlocations();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(47.624561, -122.356445),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
function popinformation(data){
var json = <?php getalerts(); ?>
console.log(json);
}
Update:
Here's what I was trying, from what I've read I have a misunderstanding of php/javascript. This is all my code within the file. Colors appear fine but pop-ups do not appear, Console reports Uncaught SyntaxError: Unexpected token < which will go away if I delete the final script. I think that means the error is within the echo json_encode($results) somehow.
<?php
function getjson(){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, lng, lat FROM information WHERE username = '" . $_SESSION['user_name'] . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
$colors = array(3 => 'red', 4 => 'yellow', 5 => 'green');
$results = array();
while ($row = $result->fetch_assoc()){
$results[$row['id']] = $row;
echo '<div class="content" style = "background-color: ' . $colors[$row['status']] . '" data-id="' . $row["id"] . '"> ' . $row["address"] . "</div>";
}
$db_connection->close();
}
function getalerts($id){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT date, id, address, status FROM information WHERE id = '" . $id . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
?>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script>
function getlocations(){
var data = <?php echo getjson(); ?>;
var i = 0;
var locations = new Array();
for(i; i < data.length; i++){
var dataholder = [data[i].misc, parseFloat(data[i].lat), parseFloat(data[i].lng)];
locations.push(dataholder);
}
return locations;
}
function createmap(){
var locations = getlocations();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(47.624561, -122.356445),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</script>
<script>
$(document).ready(function() {
var information_object = <?php echo json_encode($results); ?>;
$(".content").click(function() {
var info = information_object[$(this).data('id')];
if (info) {
alert("Address: " + info.address + "\nDate: " + info.date + "\nStatus: " + info.status);
} else {
alert("Invalid ID: " + id);
}
});
});
My html Document
<html>
<head>
<link rel="stylesheet" href="css/logged_in.css">
<?php
include("login_php_scripts.php");
?>
</head>
<body>
<div id="navigation">
Account
Logout
</div>
<div id="header">
<div id="logo"></div>
<div id="header_text"></div>
</div>
<div id="content_wrapper">
<div id="list_view">
I am logged in as: <?php echo $_SESSION['user_name']; ?></br>
<?php
getwarnings();
?>
</div>
<div id="map">
<script>
createmap();
</script>
</div>
</div>
<div id="footer"></div>
</body>
</html>
Put all the database results into an array, then convert that to a Javascript object that your popup function can look up by ID.
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
$colors = array(3 => 'red', 4 => 'yellow', 5 => 'green');
$results = array();
while ($row = $result->fetch_assoc()){
$results[$row['id']] = $row;
echo '<div class="content" style = "background-color: ' . $colors[$row['status']] . '" data-id="' . $row["id"] . '"> ' . $row["address"] . "</div>";
}
$db_connection->close();
?>
<script>
$(document).ready(function() {
var information_object = <?php echo json_encode($results); ?>;
$(".content").click(function() {
var info = information_object[$(this).data('id')];
if (info) {
alert("Address: " + info.address + "\nDate: " + info.date + "\nStatus: " + info.status);
} else {
alert("Invalid ID: " + id);
}
});
});
</script>
<?php
}

Google Map is not appearing when connecting to database

I want to retrieve geocodes from a database using PHP and MySQL with JSON. It works by selecting an option from a drop-down list and reading the matching data. I think the functions of PHP and MySQL are working correctly is just some problem with JavaScript and the map.
Code for the JavaScript:
<div data-role="content" id="accommodation">
<div id="Manu">
<select id="Cheltenham"></select>
<!--Map-->
<div id="myMap">
<script type="text/javascript">
/* call the php that has the php array which is json_encoded */
$.getJSON('cheltenham.php', function(data){
/* data will hold the php array as a javascript object */
$.each(data, function(key, val){
var x = document.getElementById("Cheltenham");
var option = document.createElement("option");
option.text = val.BUSTYPE;
option.value = val.REFERENCE;
x.add(option);
})
});
function initialize(){
$(document).on('click', '#Cheltenham', function() {
var referenceID = $(this).selected.value;
$.getJSON('SearchBusinesses.php?ReferenceID='+referenceID, function(data) {
ev_ref = data.REFERENCE;
ev_busid = data.BUSID
ev_name = data.NAME;
lat = parseFloat(data.LATITUDE);
longi = parseFloat(data.LONGITUDE);
});
var map;
var myLatlng = new google.maps.LatLng(lat,longi);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
showMarker();
function showMarker() {
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({'latLng': myLatlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var marker = new google.maps.Marker({map: map, position:results[0].geometry.location});
infowindow.setContent(ev_name + '<br/>' + lat + '<br/>' + long);
infowindow.open(map, marker);
}
}
});
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</div>
</div>
</div>
Code for cheltenham.php:
<?php
$servername = "localhost";
$username = "secret";
$password = "secret";
$dbname = "secret";
function getEventList(){
global $servername, $username, $password, $dbname;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `BUSINESS_TYPE`";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
//echo "0 results" . "<br>";
}
$conn->close();
echo json_encode($rows);
}
getEventList();
?>
Code for SearchBusinesses.php
<?php
$servername = "localhost";
$username = "secret";
$password = "secret";
$dbname = "secret";
$evReference = $_GET['REFERENCE'];
function getEventOne(){
global $servername, $username, $password, $dbname, $evName;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `LATITUDE`, `LONGITUDE` FROM `BUSINESSES` where `REFERENCE` = '" . $evReference . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
echo json_encode($row);
} else {
//echo "0 results" . "<br>";
}
$conn->close();
}
getEventOne();
?>
add this line to cheltenham.php
echo json_encode($rows, JSON_FORCE_OBJECT);

Leaflet Show all Markers from Database to Map

First I want to Demonstrate my code before asking my Question.
The code below will show all of my data from Database to my Webpage
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbmarker";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from tblmarker";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br>",$row["lat"]," &nbsp &nbsp &nbsp &nbsp &nbsp ",$row["lng"] ;
}
} else {
echo "0 results";
}
$conn->close();
?>
and this is the output of my code that will show all of the Lat/Long
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
My question is how can i connect this output in this code?
var note = document.getElementById('note');
var datepick = document.getElementById('demo1');
var timepick = document.getElementById('timepick');
layerpoly.on('click', function(e){
var markerA = new L.Marker(e.latlng,{icon: Icon1});
markerA.bindPopup("</a><br><strong>FIRE</strong></br><strong>Date:</strong>"+datepick.value+"</br><strong>Time:</strong>"+timepick.value+"</br><strong>Address:</strong>"+note.value+"<strong><br><strong>Suspect Sketch</strong><br><a href=legends/suspect.jpg rel=lightbox><img src = legends/suspect.jpg height=100 width = 100/>").addTo(map);
closure1 (markerA)
Or to simplify my Question, How can i Fetch those outputs and convert them as Leaflet Lat/long of my marker? What will happen is that get the lat/long and put a marker on the map when the webpage finish load. TY
you can create your array within the php data for examples:
$data = array();
echo " var latlong = [ " ;
for ( $x = 0; $x < mysql_num_rows( $query); $x++) {
$data[] = mysql_fetch_assoc( $query);
echo " [ " , $data[ $x][ 'lat' ], " , " , $data[ $x][ 'long' ], " ] " ;
if ( $x <= ( mysql_num_rows( $query) - 2) ) {
echo " , " ;
}
}
echo " ]; " ;
This piece of code adjusted to your fields creates the var latlong and in your case gets the output of:
latlong = [
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012]];
Then you simply add your php into the map page like:
<?php include 'latlong.php' ?>
and a function for the points to be displayed like:
for ( var i = 0; i < latlong.length; i ++) {
marker = new L.marker([latlong[i][ 1 ],latlong[i][ 2]])
.addTo(map);
}

Google Maps Markers not showing in IE

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
});

Categories