I hope I am asking this the correct way and thanks in advance for any advice! I have been trying to utilize this tutorial for a part on my own site:
https://developers.google.com/maps/documentation/javascript/mysql-to-maps
After trying many versions of my own code unsuccessfully, I decided to go ahead and step by step walk through the tutorial - even creating a new MYSQL DB exactly like in the tutorial...
In the tutorial example, they use an actual .xml file to read the data from:
// Change this depending on the name of your PHP or XML file
downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
However, just like the commented line says above the code "PHP File" - meaning you could use a PHP file there instead of an .xml file which would then dynamically generate the XML code based on the DB query.
They show 3 different ways to get the XML code from the DB and I have tried all 3 ways with the same exact results.
When I run the index.html page I get just the map showing up with no markers at all
If I run just the php file that generates the XML code, nothing shows up in the browser (just a blank white page) -- HOWEVER -- when I view the page source, it shows me the XML perfectly!
If I take that generated XML from my PHP file and copy/paste it into an .xml file and then call that .xml file in the downloadurl function, it all works perfectly!
So, therein lies my question.
What piece am I missing that would allow me to use the PHP file to dynamically generate the XML versus needing a separate XML file in my directory too.
The code I am using is the same exact code they have in the tutorial page.
Thanks in advance!!
EDIT - here are the 2 php pages. The convert-xml.php is for generating the info from MYSQL db. It's, getting the info from the db because when I view source it shows the xml tree like it should be. It;'s just not writing it to the browser or working in the downloadurl function to display the markers on the map.
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Using MySQL and PHP with Google Maps</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var customLabel = {
restaurant: {
label: 'R'
},
bar: {
label: 'B'
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(-33.863276, 151.207977),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('convert-xml.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
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() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY_IS_HERE&callback=initMap">
</script>
</body>
</html>
convert-xml.php
<?php require 'conn-info.php';?>
<?php
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false
$dom->formatOutput = true;
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// connect to db
$membermap_conn = mysql_connect($membermap_server, $membermap_user, $membermap_password, $membermap_database);
if ($membermap_conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $membermap_conn->connect_errno . ") " . $membermap_conn->connect_error; }
// select the db
$db_selected = mysql_select_db($membermap_database, $membermap_conn);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Pull the zip / user information out of the database.
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// Add to XML document node
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("id",$row['id']);
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("type", $row['type']); }
echo $dom->saveXML();
?>
Related
I'm currently using DOM Parser for my project. Also, I'm using CURL in php to scraping the website. I want to get a value from the script tag in the head of the HTML I get. But I really confused how to do that. If run the code bellow :
$data_dom = new simple_html_dom();
$data_dom->load($html);
foreach($data_dom->find('script') as $script){
echo $script->plaintext."<br>";
}
The result was the empty value, when I inspect it, only br tag appear. I want to get everything that using script tag. Here is the head value :
<head>
I will give you the script I want to get
.....
<script type="text/javascript">
var keysearch = {"departureLabel":"Surabaya (SUB : Juanda) Jawa Timur Indonesia","arrivalLabel":"Palangkaraya (PKY : Tjilik Riwut | Panarung) Kalimantan Tengah Indonesia","adultNum":"1","childNum":"0","infantNum":"0","departure":"SUB","arrival":"PKY","departDate":"20181115","roundTrip":0,"cabinType":-1,"departureCode":"ID-Surabaya-SUB","arrivalCode":"ID-Palangkaraya-PKY"};
(function(window, _gtm, keysearch){
if (window.gtmInstance){
var departureExp = keysearch.departureCode.split("-");
var arrivalExp = keysearch.arrivalCode.split("-");
gtmInstance.setFlightData({
'ITEM_TYPE': 'flight',
'FLY_OUTB_CODE': departureExp[2],
'FLY_OUTB_CITY': departureExp[1],
'FLY_OUTB_COUNTRYCODE': departureExp[0],
'FLY_OUTB_DATE': keysearch.departDate,
'FLY_INB_CODE': arrivalExp[2],
'FLY_INB_CITY': arrivalExp[1],
'FLY_INB_COUNTRYCODE': arrivalExp[0],
'FLY_INB_DATE': keysearch.returnDate,
'FLY_NBPAX_ADL': keysearch.adultNum,
'FLY_NBPAX_CHL': keysearch.childNum,
'FLY_NBPAX_INF': keysearch.infantNum,
});
gtmInstance.pushFlightSearchEvent();
}
}(window, gtmInstance, keysearch));
var key = "rkey=10fe7b6fd1f7fa1ef0f4fa538f917811dbc7f4628a791ba69962f2ed305fb72d061b67737afd843aaaeeee946f1442bb";
var staticRoot = 'http://sta.nusatrip.net';
$(function() {
$("#currencySelector").nusaCurrencyOptions({
selected: getCookie("curCode"),
});
});
</script>
</head>
I want to get the key variable. I will use it to get the data from the website. Thanks
Depending on what the rest of the markup looks like, you may be able to just use DOMDocument and XPath, then parse out the value of the var with preg_match. This example will echo the key.
<?php
$html = <<<END
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
var keysearch = {"departureLabel":"Surabaya (SUB : Juanda) Jawa Timur Indonesia","arrivalLabel":"Palangkaraya (PKY : Tjilik Riwut | Panarung) Kalimantan Tengah Indonesia","adultNum":"1","childNum":"0","infantNum":"0","departure":"SUB","arrival":"PKY","departDate":"20181115","roundTrip":0,"cabinType":-1,"departureCode":"ID-Surabaya-SUB","arrivalCode":"ID-Palangkaraya-PKY"};
(function(window, _gtm, keysearch){
if (window.gtmInstance){
var departureExp = keysearch.departureCode.split("-");
var arrivalExp = keysearch.arrivalCode.split("-");
gtmInstance.setFlightData({
'ITEM_TYPE': 'flight',
'FLY_OUTB_CODE': departureExp[2],
'FLY_OUTB_CITY': departureExp[1],
'FLY_OUTB_COUNTRYCODE': departureExp[0],
'FLY_OUTB_DATE': keysearch.departDate,
'FLY_INB_CODE': arrivalExp[2],
'FLY_INB_CITY': arrivalExp[1],
'FLY_INB_COUNTRYCODE': arrivalExp[0],
'FLY_INB_DATE': keysearch.returnDate,
'FLY_NBPAX_ADL': keysearch.adultNum,
'FLY_NBPAX_CHL': keysearch.childNum,
'FLY_NBPAX_INF': keysearch.infantNum,
});
gtmInstance.pushFlightSearchEvent();
}
}(window, gtmInstance, keysearch));
var key = "rkey=10fe7b6fd1f7fa1ef0f4fa538f917811dbc7f4628a791ba69962f2ed305fb72d061b67737afd843aaaeeee946f1442bb";
var staticRoot = 'http://sta.nusatrip.net';
$(function() {
$("#currencySelector").nusaCurrencyOptions({
selected: getCookie("curCode"),
});
});
</script>
</head>
<body>foo</body>
</html>
END;
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$result = $xpath->query('//script');
foreach($result as $currScriptTag)
{
$currScriptContent = $currScriptTag->nodeValue;
$matchFound = preg_match('/var key = "(.*)"/', $currScriptContent, $matches);
if($matchFound)
{
/*
* $matches[0] will contain the whole line like var key = "..."
* $matches[1] just contains the value of the var
*/
$key = $matches[1];
echo $key.PHP_EOL;
}
}
I am trying to read a csv file in a ftp server using php .
Below is my code:-
maps.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Circles</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
// This example creates circles on the map, representing
// populations in North America.
// First, create an object containing LatLng and population for each city.
var citymap = [];
var temp = [];
<?php
$data = array();
$file = fopen("ftp://b7_15716007:xxxxxx#ftp.byethost7.com/htdocs/data.csv","r");
while(!feof($file))
{
$data = fgetcsv($file);
?>
temp.push("<?php echo $data[0]; ?>");
temp.push("<?php echo $data[1]; ?>");
temp.push("<?php echo $data[2]; ?>");
temp.push("<?php echo $data[3]; ?>");
citymap.push(temp);
console.log(citymap);
temp = [];
<?php
}
fclose($file);
?>
var cityCircle;
function initialize() {
// Create the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
var fillcolor=[];
fillcolor[0]='#FF0000';fillcolor[1]='#FFFF00'; fillcolor[2]='#FF00FF'; fillcolor[3]='#00FF00';
var loop=0;
for (i = 0; i < citymap.length; i++) {
var populationOptions = {
strokeColor: '#000000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: fillcolor[loop],
fillOpacity: 0.35,
map: map,
center: new google.maps.LatLng(citymap[i][1], citymap[i][2]),
radius: Math.sqrt(citymap[i][3]) * 100000
};
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle(populationOptions);
// cityCircle = new google.maps.Circle(populationOptions1);
loop=loop+1;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
This code has to read the values in csv and represent them in a google map api .
But the code is not working .
Can anyone please help me fix this .
The link for the csv is
Even after passing the url with authentication I dont get the map being displayed .
You cannot just open password protected ftp resource like that.. You must use password for entering there.
Please, try to use some authentication functions like:
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// try to download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}
Refer to: http://php.net/manual/en/function.ftp-get.php for more information.
I'm using html5 canvas to capture a signature and store it in MySQL. I've got everything in the script working except for the part that saves the signature and sends it to MySQL.
My knowledge of AJAX is none so I'm working off what I read in books, see on tutorials and get help on from here.
So in Firefox console when I click on save signature I can see the script displays the post.php file it's supposed to go to and displays a 200 ok notification but nothing happens, it doesn't post in MySQL (which doesn't surprise me as I'm sure my code is incorrect) and I don't see any errors.
What I want to accomplish is to upload the signature image to a folder on the server and save the path to the image in MySQL. Being unfamiliar with JavaScript, Jquery and Ajax I'm confused with how to get this to function.
Here is the jquery:
$(document).ready(function () {
/** Set Canvas Size **/
var canvasWidth = 400;
var canvasHeight = 75;
/** IE SUPPORT **/
var canvasDiv = document.getElementById('signaturePad');
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if (typeof G_vmlCanvasManager != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
}
var context = canvas.getContext("2d");
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
/** Redraw the Canvas **/
function redraw() {
canvas.width = canvas.width; // Clears the canvas
context.strokeStyle = "#000000";
context.lineJoin = "miter";
context.lineWidth = 2;
for (var i = 0; i < clickX.length; i++) {
context.beginPath();
if (clickDrag[i] && i) {
context.moveTo(clickX[i - 1], clickY[i - 1]);
} else {
context.moveTo(clickX[i] - 1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke();
}
}
/** Save Canvas **/
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
$("#imgData").html('Thank you! Your signature was saved');
var ajax = XMLHttpRequest();
ajax.open("POST", 'post.php');
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(sigData);
// $('#debug').html(sigData);
});
/** Clear Canvas **/
$('#clearSig').click(
function clearSig() {
clickX = new Array();
clickY = new Array();
clickDrag = new Array();
context.clearRect(0, 0, canvas.width, canvas.height);
});
/**Draw when moving over Canvas **/
$('#signaturePad').mousemove(function (e) {
if (paint) {
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
/**Stop Drawing on Mouseup **/
$('#signaturePad').mouseup(function (e) {
paint = false;
});
/** Starting a Click **/
function addClick(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
$('#signaturePad').mousedown(function (e) {
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
});
and here is the PHP: Also I didn't write the php code below it's part of the entire signature pad so I'm sure it's not correct.
<?php
session_start();
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$session_id = $_SERVER['REMOTE_ADDR'];
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
$imageName = "sign_" . rand(5,1000) . rand(1, 10) . rand(10000, 150000) . rand(1500, 100000000) . ".png";
//Set the absolute path to your folder (i.e. /usr/home/your-domain/your-folder/
$filepath = "xampp/htdocs/alpha/site7/images/" . $imageName;
$fp = fopen("$filepath", 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
//Connect to a mySQL database and store the user's information so you can link to it later
$link = mysql_connect('localhost','root', 'password') OR DIE(mysql_error);
mysql_select_db("customer", $link);
mysql_query("INSERT INTO 'signature' ('session', 'image_location') VALUES ('$session_id', '$imageName')") OR DIE(mysql_error());
mysql_close($link);
}
?>
And the html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Signature Pad</title>
<!-- The Signature Pad -->
<script type ="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="signature-pad.js"></script>
</head>
<body>
<center>
<fieldset style="width: 435px">
<br/>
<br/>
<div id="signaturePad" style="border: 1px solid #ccc; height: 55px; width: 400px;"></div>
<br/>
<button id="clearSig" type="button">Clear Signature</button>
<button id="saveSig" type="button">Save Signature</button>
<div id="imgData"></div>
<div
<br/>
<br/>
</fieldset>
</center>
<div id="debug"></div>
</body>
</html>
After some head beating over this I've finally been able to discover some errors.
After signing the signature pad and pressing the save signature button I get these errors in Firebug
Warning: fopen(xampp/htdocs/alpha/site6/images/sign_42281643871777767.png): failed to open stream: No such file or directory in C:\xampp\htdocs\alpha\site6\post.php on line 20
Warning: fwrite() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\alpha\site6\post.php on line 21
Warning: fclose() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\alpha\site6\post.php on line 22
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''signatures' ('session', 'image_location') VALUES ('127.0.0.1', 'sign_42281643871' at line 1
Since I don't have any knowledge of Jquery or Ajax and how they are creating the image and attempting to post it to a folder I'm pretty much stuck at this point!
seems I'm answering my own problems, I've figured out what the fopen errors were, I wasn't using an absolute path so adding a / before the start of the path cleared up everything except for the last error of this:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''signature' ('session', 'image_location') VALUES ('127.0.0.1', 'sign_11814198867' at line 1
Hi I'm having some problems making my function structure. Would appreciate any help.
First this function should delete map markers once OnChange event is triggered from index.php.
And send post values to xmlmapquery.php for data retrieval.
once retrieved, The data should be stored back to my index.php in <div id='content'>
function filter()
{
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
var lgu = $('#lgu').val();
var category = $('#category').val();
var type = $('#type').val();
$.get('xmlmapquery.php', { filter: lgu, filter2: category, filter3: type},function(data){
$('#content').text(data);
)};
};
Now this is xmlmapquery.php
<?php
include('connection_db.php');
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
if(isset($_POST['filter']) && isset($_POST['filter2']) && isset($_POST['filter3'])){
$query = "SELECT * FROM markers WHERE type='".$_POST['filter']."' and type='".$_POST['filter2']."'
and type='".$_POST['filter3']."'";
}
// Select all the rows in the markers table
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("type", $row['type']);
}
echo $dom->saveXML();
?>
Would appreciate help on this. currently the function is NOT working even deleting the markers is not working. Once i get this thing working I will add more commands to the function that would get data and create new markers for my map. Thanks in advance.
Suppose your script logic is ok, and no die() or other php methods are returning null or false (anyway you should see in your browser console).
Things to do are:
1 - check firebug/chrome/browser console when launching request (if the request is hidden in some way use the "save" request method in console to check that)
2 - use var_dump($dom->saveXML()); instead of echo $dom->saveXML();
3 - check server/php logs when possible
4 - be sure your request uirl is complete and working and i'm referring to $.get('xmlmapquery.php');
if you follow this line of debugging, unless ghosts doesn't exists, you will be able to run your script easly.
Hope it will help
I'm making a Google Map that will pull information from a database and output xml to be interpreted into markers on the map. I want to pass the clicked elements id into the PHP to filter the database results. When the function is executed, I get an error stating "cannot read property '_e3' of undefined". Everything works fine when I get rid of the variable and directly enter a type into the code.
relevant jQuery
$(document).ready(function() {
$('.map_item').toggle(
function() {
var itemid = this.id;
$.ajax({
type: 'POST',
//php script takes info from database, outputs xml
url:'SQL.php',
//pass var to the php to select only items matching this id
data: 'variable1=' + itemid,
success: function(data) {
relevant PHP from file SQL.php
$ajax_var = $_POST['variable1'];
$query = 'SELECT * FROM location WHERE Type="' . $ajax_var . '"';
$result = mysql_query($query); //sqlsrv_query
header('Content-type: text/xml');
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement('marker');
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("dirtType",$row['dirtType']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
}
echo $dom->saveXML();
I would say that the data should be sent in a different way, like this:
data: {
"variable1": itemId
}