I wonder whether someone may be able to help me please.
I am using the following pieces of coding to successfully show map markers at particular locations held within a mySQL database.
PHP CODE
<?php
require("phpfile.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$connection=mysql_connect ("hostname", $username, $password);
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT locationid, detectorid, searchheadid FROM finds WHERE `locationid` = '43'";
$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("locationid",$row['locationid']);
$newnode->setAttribute("detectorid",$row['detectorid']);
$newnode->setAttribute("searchheadid",$row['searchheadid']);
}
echo $dom->saveXML();
?>
HTML CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Location</title>
<link rel="stylesheet" href="css/findsperlocationstyle.css" type="text/css" media="all" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
var customIcons = {
Artefact: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Coin: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Jewellery: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
// Creating a LatLngBounds object
var bounds = new google.maps.LatLngBounds();
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:14,
mapTypeId: 'satellite'
});
// Change this depending on the name of your PHP file
downloadUrl("phpfile.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var locationid = markers[i].getAttribute("locationid");
var detectorid = markers[i].getAttribute("detectorid");
var searchheadid= markers[i].getAttribute("searchheadid");
var icon = customIcons[findcategory] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
title: 'Click to view details',
icon: icon.icon,
shadow: icon.shadow,
formdetectorid: detectorid,
formsearchheadid: searchheadid,
});
bounds.extend(point);
map.fitBounds(bounds);
google.maps.event.addListener(marker, "click", function() {
document.getElementById('detectorid').value = this.formdetectorid;
document.getElementById('searchheadid').value = this.formsearchheadid;
});
}
});
}
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>
</head>
<body onLoad="load()">
<form name="findsperlocation" id="findsperlocation">
<p align="left"><label>Location id<br />
</label>
</p>
<div>
<div align="left">
<input name="locationid" type="text" id="locationid" value="43" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Detector Used</label> </p>
<div>
<div align="left">
<input name="detectorid" type="text" id="detectorid" size="30" maxlength="30"/>
</div>
</div>
<p align="left"><label>Search Head Used</label> </p>
<div>
<div align="left">
<input name="searchheadid" type="text" id="searchheadid" size="30" maxlength="30"/>
</div>
</div>
</form>
<div id="map"></div>
</body>
</html>
The problem I have concerns two of my fields, 'detectorid' and 'searchheadid'. The information for these fields is saved via two drop down menus on another form. The drop down menus show the appropiate text values for the user to choose, but the 'id' value associated with each selection is saved to the table which is being used in the above pieces of code.
What I would like to be able to do, if at all possible, is rather than the 'id' value being shown in this form, I would like to convert it back to the appropriate text value. The text values are held in two separate tables, 'detectors' and 'searchheads' but I must admit, I'm really not sure where to begin.
I just wondered whether it would be at all possible please that someone could show me what I need to do to show this information.
Many thanks and kind regards
Chris
Well, generally when you have a dropdown, each <option> has a value= and a content.
For example, you can retrieve the right list of ID and titles from the database, and the list should look as follows for example:
<select name="id">
<option value="1567">My City</option><!-- this is ID=1567 with title=My City-->
<option value="1322">Example City</option><!-- this is ID=1322 and title=Example City-->
</select>
The form, when submitted, returns the correct ID chosen from the dropdown and not its title.
All you have to worry about is having an SQL query give you the list of locations with their IDs, and you just loop through them and make them generate a list with the above format.
An example PHP & MySQL code would be simply:
<?php
$query = mysql_query("SELECT * FROM `saved_locations` WHERE `user` = '{$myUser}'");
echo '<select name="id">';
while ($row = mysql_fetch_object($query)) {
echo '
<option id="'.$row->id.'">'.$row->title.'</option>';
}
echo '
</select>';
?>
Related
This question already has answers here:
Google Maps API autocomplete 2nd address fields on same page
(3 answers)
jQuery and google maps auto complete
(2 answers)
Closed 3 years ago.
I am trying to add two Google Maps Autocomplete search boxes in one html page. However, the moment I copy the same code with same API only one of them works.
<body>
<div class="pac-card" id="pac-card">
<div id="pac-container">
<input id="pac-input" type="text"
placeholder="Enter a location">
</div>
</div>
<div id="map"></div>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var card = document.getElementById('pac-card');
var input = document.getElementById('pac-input');
var types = document.getElementById('type-selector');
var strictBounds = document.getElementById('strict-bounds-selector');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
var autocomplete = new google.maps.places.Autocomplete(input);
// Bind the map's bounds (viewport) property to the autocomplete object,
// so that the autocomplete requests use the current map bounds for the
// bounds option in the request.
autocomplete.bindTo('bounds', map);
// Set the data fields to return when the user selects a place.
autocomplete.setFields(
['address_components', 'geometry', 'icon', 'name']);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
radioButton.addEventListener('click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-address', ['address']);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
document.getElementById('use-strict-bounds')
.addEventListener('click', function() {
console.log('Checkbox clicked! New state=' + this.checked);
autocomplete.setOptions({strictBounds: this.checked});
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=My API KEY&libraries=places&callback=initMap"
async defer></script>
I've checked all possible questions in stack with respect to this topic and none of them used an API key which was the main reason for me posting this question. I ran all those codes that I found online but none worked perfectly.
To those who have the same problem as me, Here's the solution..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Maps API v3 Multiple Autocomplete Inputs</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
type="text/javascript"
src="/js/lib/dummy.js"
></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=Your API Code &libraries=places"></script>
<style id="compiled-css" type="text/css">
.autocomplete {
width:300px;
}
</style>
<!-- TODO: Missing CoffeeScript 2 -->
<script type="text/javascript">//<![CDATA[
var VanillaRunOnDomReady = function() {
function initialize() {
var acInputs = document.getElementsByClassName("autocomplete");
for (var i = 0; i < acInputs.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(acInputs[i]);
autocomplete.inputId = acInputs[i].id;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
document.getElementById("log").innerHTML = 'You used input with id ' + this.inputId;
});
}
}
initialize();
}
var alreadyrunflag = 0;
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", function(){
alreadyrunflag=1;
VanillaRunOnDomReady();
}, false);
else if (document.all && !window.opera) {
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag = document.getElementById("contentloadtag")
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete"){
alreadyrunflag=1;
VanillaRunOnDomReady();
}
}
}
window.onload = function(){
setTimeout("if (!alreadyrunflag){VanillaRunOnDomReady}", 0);
}
//]]></script>
</head>
<body>
<input class="autocomplete" id="ac1" placeholder="Enter your address" type="text">
<br />
<br />
<input class="autocomplete" id="ac2" placeholder="Enter your address" type="text">
<br />
<br />
<input class="autocomplete" id="ac3" placeholder="Enter your address" type="text">
<br />
<br />
<span id="log"></span>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "42usv81j"
}], "*")
}
// always overwrite window.name, in case users try to set it manually
window.name = "result"
</script>
</body>
</html>
I have a very simple form that has a field for a title and uses quill to enter a discussion. I have tried everything I can think of, but still cannot populate a mysql database with the information. I think I'm getting close, but am not quite there yet. I think the problem lies in my use of json and ajax.
Here is my html file that creates the form:
<!DOCTYPE>
<html>
<head>
<title>Discussions</title>
<meta charset="UTF-8">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.quilljs.com/1.2.2/quill.snow.css" rel="stylesheet">
<link href = "../css/discussionsEditor.css" rel = "stylesheet">
<script src="https://cdn.quilljs.com/1.2.2/quill.js"></script>
</head>
<body>
<div id="form-container" class="container">
<form id="discussionForm" method = "post" action ="discussionsEditor.php" role="form">
<div class="row">
<div class="col-xs-8">
<div class="form-group">
<input class="form-control" name="title" type="text" placeholder="Title">
</div>
</div>
</div>
<div class="row form-group">
<input name="discussionContent" type="hidden">
<div id="editor-container">
</div>
</div>
<div class="row">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</div>
<script>
var quill = new Quill('#editor-container', {
modules: {
toolbar: [
['bold', 'italic'],
['link', 'blockquote', 'code-block', 'image'],
[{ list: 'ordered' }, { list: 'bullet' }]
]
},
placeholder: 'Compose an epic...',
theme: 'snow'
});
</script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../js/discussionsEditor.js"></script>
</body>
</html>
Here is my javascript file where I try to use json and ajax to transfer the data.
var form = document.querySelector('form');
form.onsubmit = function() {
// Populate hidden form on submit
var discussionContent = document.querySelector('input[name=discussionContent]');
discussionContent.value = JSON.stringify(quill.getContents());
var url ="discussionsEditor.php";
var data = stringify(quill.getContents());
alert( "the data is " + data);
$.ajax({
type: "POST",
url : url,
data : discussionContent,
success: function ()
{
alert("Successfully sent to database");
},
error: function()
{
alert("Could not send to database");
}
});
return false;
};
and finally here is my php file
<?php
try
{
$pdo = new PDO('mysql:host=localhost; dbname=mydb', "user", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server:' . $e->getMessage();
include '../output.html.php';
exit();
}
$title = $_POST['title'];
echo "<br />";
echo "the title is " . $title;
$discussionContent = $_POST['discussionContent'];
echo "<br />";
echo "the discussion content is ". $discussionContent;
$sql = 'INSERT INTO Discussions(Title, DiscussionContent)
Values(:Title, :DiscussionContent)';
$statement = $pdo -> prepare($sql);
$statement -> execute(array(':Title' => $title, ':DiscussionContent' => $discussionContent));
?>
If I put 'Denise' in the title field and 'cute' in the quill discussion field, the echo statements in the php file give this result:
the title is Denise
the discussion content is {"ops":[{"insert":"Cute\n"}]}
Nothing is stored in the database.
I would appreciate and help or comments. Thanks
Use getText() method if you simply need a Text value from your quill editor like below:
var quillText = quill.getText();
If you are planning to store HTML data in DB use
var quillHtml = quill.root.innerHTML.trim();
pass the value to your ajax data like this:
$.ajax({
type: "POST",
url : url,
data: {editorContent : quillText },
success: function (data,status, xhr)
{
if(xhr.status == 200) {
alert("Successfully sent to database");
}
},error: function() {
alert("Could not send to database");
}
});
Reason to post as "editorContent" is that you can get the posted values simply by
$_POST['editorContent']
in your PHP script.
After further sanitization, insert the data to DB(either HTML or TEXT).
Hope it helps :-)
Please try the following.It may help to resolve the issue:
comment is editor id.
var quill = new Quill('#comment');
var cc = quill.container.firstChild.innerHTML;
Now cc will hold the data of your div element.That can be inserted into DB.It is just example.You can use if it helps you.
Easy way:
<form method="post" id="identifier">
<div id="quillArea"></div>
<textarea name="text" style="display:none" id="hiddenArea"></textarea>
<input type="submit" value="Save" />
</form>
If you give the form an identifier, then using jQuery you can do the following:
var quill = new Quill ({...}) //definition of the quill
$("#identifier").on("submit",function() {
$("#hiddenArea").val($("#quillArea").html());
})
Now once you have the HTML in the textarea simple post it by clicking submit button
If you want to get only the content, you can add .ql-editor to your selector : $("#hiddenArea").val($("#quillArea .ql-editor").html());
Quill.js is amazing rich text editor but there is very low amount of Youtube videos and google articles about it, other than that their documentation is hard to understand. So new users may have trouble using it.
Lets come to your code...
You need to remove all attributes from form tag except "id".
Your old:
<form id="discussionForm" method = "post" action ="discussionsEditor.php" role="form">
I suggest:
<form id="discussionForm" class="You Can Use Class">
Great, You have done everything fine in JS but you have passed the object wrongly while posting the data. (I also make some new changes)
JavaScript:-
Wait... I hope you haven't forgotten to use this code block in your JS.😅
var quill = new Quill('#service_details_editor', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
//var form = document.querySelector('form');
$("#discussionForm").on('submit', function (e) {
e.preventDefault();
// Populate hidden form on submit
var discussionContent = document.querySelector('input[name=discussionContent]');
discussionContent.value = JSON.stringify(quill.getContents());
var url ="discussionsEditor.php";
var form = new FormData(this);
$.ajax({
type: "POST",
url : url,
data : form,
contentType:false,
processData:false,
success: function (response) //Response which is come from "discussionsEditor.php" if Query run successfully.
{
alert("Successfully sent to database");
},
error: function(response)
{
alert("Could not send to database");
}
});
return false;
});
PHP:-
Your PHP may working well no doubt but I usually write PHP like this. 😄
//Connection Block Start
<?php
$host = "localhost";
$user = "root";
$password = '';
$db_name = "Your DB Name";
$con = mysqli_connect($host, $user, $password, $db_name);
if (mysqli_connect_errno()) {
die("Failed to connect with MySQL: " . mysqli_connect_error());
}
//Connection Block END
if (isset($_POST['title'])) {
$title = $_POST['title'];
$DiscussionContent = $_POST['DiscussionContent'];
$sql = "INSERT INTO Discussions(title,DiscussionContent) VALUES ('$title','$DiscussionContent')";
if (mysqli_query($con, $sql)) {
echo 1;
} else {
echo 0;
}
}
die();
exit;
}
How do I store the data returned by Google Places API to my database?
This is the HTML code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Creating a Custom jQuery Plugin</title>
<link type="text/css" rel="stylesheet" href="jquery.accordion.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.accordion.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('dl#my-accordion').accordion({open:true});
});
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script src="js/script.js"></script>
</head>
<body>
<div id="container"></div>
<div id="gmap_canvas"></div>
<div class="actions">
<div class="button">
<label for="gmap_where">Where:</label>
<input id="gmap_where" type="text" name="gmap_where" /></div>
<div id="button2" class="button" onclick="findAddress(); return false;">Search for address</div>
<form action="save.php" method="post">
<div class="button">
<label for="gmap_keyword">Keyword (optional):</label>
<input id="gmap_keyword" type="text" name="gmap_keyword" /></div>
<div class="button">
<label for="gmap_type">Type:</label>
<select id="gmap_type">
<option value="art_gallery">art_gallery</option>
<option value="atm">atm</option>
<option value="bank">bank</option>
<option value="bar">bar</option>
<option value="cafe">cafe</option>
<option value="food">food</option>
<option value="hospital">hospital</option>
<option value="police">police</option>
<option value="store">store</option>
</select>
</div>
<div class="button">
<label for="gmap_radius">Radius:</label>
<select id="gmap_radius">
<option value="500">500</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
<option value="5000">5000</option>
</select>
</div>
<input type="hidden" id="lat" name="lat" value="40.7143528" />
<input type="hidden" id="lng" name="lng" value="-74.0059731" />
<div onclick="findplaces(); return false;"><input type="submit" value="Search for objects"class="button" id="button1" /></div>
</form>
</div>
</body>
</html>
This is the script
var geocoder;
var map;
var markers = Array();
var infos = Array();
function initialize() {
// prepare Geocoder
geocoder = new google.maps.Geocoder();
// set initial position (New York)
var myLatlng = new google.maps.LatLng(40.7143528,-74.0059731);
var myOptions = { // default map options
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);
}
// clear overlays function
function clearOverlays() {
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
markers = [];
infos = [];
}
}
// clear infos function
function clearInfos() {
if (infos) {
for (i in infos) {
if (infos[i].getMap()) {
infos[i].close();
}
}
}
}
// find address function
function findAddress() {
var address = document.getElementById("gmap_where").value;
// script uses our 'geocoder' in order to find location by address name
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) { // and, if everything is ok
// we will center map
var addrLocation = results[0].geometry.location;
map.setCenter(addrLocation);
// store current coordinates into hidden variables
document.getElementById('lat').value = results[0].geometry.location.lat();
document.getElementById('lng').value = results[0].geometry.location.lng();
// and then - add new custom marker
var addrMarker = new google.maps.Marker({
position: addrLocation,
map: map,
title: results[0].formatted_address,
icon: 'marker.png'
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
// find custom places function
function findPlaces() {
// prepare variables (filter)
var type = document.getElementById('gmap_type').value;
var radius = document.getElementById('gmap_radius').value;
var keyword = document.getElementById('gmap_keyword').value;
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
var cur_location = new google.maps.LatLng(lat, lng);
// prepare request to Places
var request = {
location: cur_location,
radius: radius,
types: [type]
};
if (keyword) {
request.keyword = [keyword];
}
// send request
service = new google.maps.places.PlacesService(map);
service.search(request, createMarkers);
}
// create markers (from 'findPlaces' function)
function createMarkers(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// if we have found something - clear map (overlays)
clearOverlays();
// and create new markers by search result
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
} else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS) {
alert('Sorry, nothing is found');
}
}
// creare single marker function
function createMarker(obj) {
// prepare new Marker object
var mark = new google.maps.Marker({
position: obj.geometry.location,
map: map,
title: obj.name
});
markers.push(mark);
// prepare info window
var infowindow = new google.maps.InfoWindow({
content: '<img src="' + obj.icon + '" /><font style="color:#000;">' + obj.name +
'<br />Rating: ' + obj.rating + '<br />Vicinity: ' + obj.vicinity + '</font>'
});
// add event handler to current marker
google.maps.event.addListener(mark, 'click', function() {
clearInfos();
infowindow.open(map,mark);
});
infos.push(infowindow);
}
// initialization
google.maps.event.addDomListener(window, 'load', initialize);
I just need an idea on how to dump the data returned by Google Places API in a database. Thanks!
You should post the result you got from google map API to your own server, maybe using your own API, and store it on your server.
Interacting with database via Javascript is although possible, it is not recommended.
As Quentin commented "low security environment is not web programming"
So the best approach is using Web Services (via API)
It seems you need to store lat/lon to your database(if needed parse
the lat/lon returned by Google API).
Then create JSON objects out of it.
Next learn about Ajax,
which is going to send data to, and retrieve data from, a server
asynchronously (in the background) without interfering with the
display and behavior of the existing page.
Hope you understand.
I tested this code on a test page but now want to implement it on a page that is called by an overlay (Lightview). The map is not displaying and I do not know why. The overlay spaces the size of a map, but nothing shows. Here is the code:
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<?php
require_once('../maps/google.php');
if(isset($_POST['submit']))
{
$zipcode = $_REQUEST['zipcode'];
$lookupPerformed = false;
if (strlen($zipcode) > 0) {
$geocoder = new Geocoder('mykey');
try {
$placemarks = $geocoder->lookup($zipcode);
}
catch (Exception $ex) {
echo $ex->getMessage();
exit;
}
$lookupPerformed = true;
}
foreach ($placemarks as $placemark) {
$lat = $placemark->getPoint()->getLatitude();
$long = $placemark->getPoint()->getLongitude();
}
?>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
A Company: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.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(<?php echo $lat;?>, <?php echo $long;?>),
zoom: 10,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("../testxml.php?zipcode=<?php echo $zipcode;?>", 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 point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
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() {}
//]]>
</script>
///// other PHP code
</head>
<form method="POST" id="ajaxForm" onsubmit="submitAjaxFormDemonstration()">
<input type="text" size="10" maxlength="10" name="zipcode" tabindex="1" value=" <?php echo $_POST['zipcode'];?>" />
<input type="submit" id="submit" value="Search" name="submit" tabindex="2" />
</form>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
You have a pile of things going wrong here, and somethings which I can't even see to tell you whether they are right or wrong...
At the bottom of the posted code, you have:
</head>
<form method="POST" id="ajaxForm" onsubmit="submitAjaxFormDemonstration()">
<input type="text" size="10" maxlength="10" name="zipcode" tabindex="1" value=" <?php echo $_POST['zipcode'];?>" />
<input type="submit" id="submit" value="Search" name="submit" tabindex="2" />
</form>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
You have a <form>...</form> element declared outside of the <body>...</body> tags - this is not valid HTML.
</head>
<body onload="load()">
<form method="POST" id="ajaxForm" onsubmit="submitAjaxFormDemonstration()">
<input type="text" size="10" maxlength="10" name="zipcode" tabindex="1" value="<?php echo $_POST['zipcode'];?>" />
<input type="submit" id="submit" value="Search" name="submit" tabindex="2" />
</form>
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
Fixes that... But you should probably use something like the W3C Validator to check your HTML code. Bad HTML will almost always break Javascript (like Google Maps).
Next, you are invoking a PHP script which you do not explain at all require_once('../maps/google.php');. What is it? Where did you get it? Have you consulted their Tutorials or Documentation?
You are only showing us part of the problem here. You need to go back to Square 1 and check each step as you move forwards. Jumping to the end (which, from the looks of your code, is what you've tried to do) means that one of the hundred steps between Square 1 and there may have broken, and now you have to go back and look for it.
I am using the PHP and AJAX coding below to populate a map showing various markers for a given location stored in a mySQL database.
The markers are correctly shown but what I would like to be able to do is to populate the fields on my form with the associated data from the database, so that as each marker is clicked the fields will show the data pertient to that marker.
PHP Code
<
?php
require("phpfile.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$connection=mysql_connect ("hostname", $username, $password);
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT findid, locationid, findosgb36lat, findosgb36lon, dateoftrip, findcategory, findname, finddescription, pasref, findimage, additionalcomments FROM finds WHERE `locationid` = '2'";
$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("findid",$row['findid']);
$newnode->setAttribute("locationid",$row['locationid']);
$newnode->setAttribute("findosgb36lat",$row['findosgb36lat']);
$newnode->setAttribute("findosgb36lon",$row['findosgb36lon']);
$newnode->setAttribute("dateoftrip",$row['dateoftrip']);
$newnode->setAttribute("findcategory",$row['findcategory']);
$newnode->setAttribute("findname",$row['findname']);
$newnode->setAttribute("finddescription",$row['finddescription']);
$newnode->setAttribute("pasref",$row['pasref']);
$newnode->setAttribute("findimage",$row['findimage']);
$newnode->setAttribute("additionalcomments",$row['additionalcomments']);
}
echo $dom->saveXML();
?>
HTML Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Finds Per Location</title>
<link rel="stylesheet" href="css/findsperlocationstyle.css" type="text/css" media="all" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
var customIcons = {
Artefact: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Coin: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Jewellery: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
// Creating a LatLngBounds object
var bounds = new google.maps.LatLngBounds();
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:14,
mapTypeId: 'satellite'
});
// Change this depending on the name of your PHP file
downloadUrl("phpfile.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var findid = markers[i].getAttribute("findid");
var locationid = markers[i].getAttribute("locationid");
var dateoftrip = markers[i].getAttribute("dateoftrip");
var findcategory = markers[i].getAttribute("findcategory");
var findname = markers[i].getAttribute("findname");
var finddescription = markers[i].getAttribute("finddescription");
var pasref = markers[i].getAttribute("pasref");
var findimage= markers[i].getAttribute("findimage");
var additionalcomments= markers[i].getAttribute("additionalcomments");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("findosgb36lat")),
parseFloat(markers[i].getAttribute("findosgb36lon")));
var icon = customIcons[findcategory] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
title: 'Click to view details',
icon: icon.icon,
shadow: icon.shadow
});
bounds.extend(point);
map.fitBounds(bounds);
}
});
}
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>
</head>
<body onLoad="load()">
<form name="findsperlocation" id="findsperlocation">
<p align="left"><label>Location id<br />
</label>
</p>
<div>
<div align="left">
<input name="locationid" type="text" id="locationid" value="2" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Date of Trip<br />
</label>
</p>
<div>
<div align="left">
<input name="dateoftrip" type="text" id="dateoftrip" readonly="readonly"/>
</div>
</div>
<p align="left">
<label></label>
<label>Find Category</label>
</p>
<div>
<div align="left">
<input name="findcategory" type="text" id="findcategory" size="10"readonly="readonly"/>
</div>
</div>
<p align="left">
<label>Find Name</label>
</p>
<div>
<div align="left">
<input name="findname" type="text" id="findname" size="35" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Find Description</label> </p>
<div>
<div align="left">
<input name="finddescription" type="text" id="finddescription" size="100"readonly="readonly"/>
</div>
</div>
<p align="left">
<label>
<label>PAS Ref. </label>
</p>
<div>
<div align="left">
<input name="pasref" type="text" id="pasref" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Additional Comments</label>
</p>
<div>
<div align="left">
<textarea name="additionalcomments" cols="50" rows="12" id="additionalcomments" readonly="readonly"></textarea>
</div>
</div>
<p align="left"><br />
</label>
</p>
<div>
<div align="left"></div>
</div>
</form>
<div id="map"></div>
</body>
</html>
I think I'm half way there because I'm mangaing to pull all of the information from the database. I can see this when I run the php script in my web browser, but I'm just not sure what to do for the next step.
What do I need to do next?
UPDATED CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Finds Per Location</title>
<link rel="stylesheet" href="css/findsperlocationstyle.css" type="text/css" media="all" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
var customIcons = {
Artefact: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Coin: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Jewellery: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
// Creating a LatLngBounds object
var bounds = new google.maps.LatLngBounds();
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:14,
mapTypeId: 'satellite'
});
// Change this depending on the name of your PHP file
downloadUrl("phpfile.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var findid = markers[i].getAttribute("findid");
var locationid = markers[i].getAttribute("locationid");
var dateoftrip = markers[i].getAttribute("dateoftrip");
var findcategory = markers[i].getAttribute("findcategory");
var findname = markers[i].getAttribute("findname");
var finddescription = markers[i].getAttribute("finddescription");
var detectorname = markers[i].getAttribute("detectorname");
var searchheadname = markers[i].getAttribute("searchheadname");
var detectorsettings = markers[i].getAttribute("detectorsettings");
var pasref = markers[i].getAttribute("pasref");
var findimage= markers[i].getAttribute("findimage");
var additionalcomments= markers[i].getAttribute("additionalcomments");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("findosgb36lat")),
parseFloat(markers[i].getAttribute("findosgb36lon")));
var icon = customIcons[findcategory] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
title: 'Click to view details',
icon: icon.icon,
shadow: icon.shadow,
formdateoftrip: "dateoftrip",
formfindcategory: "findcategory"
});
bounds.extend(point);
map.fitBounds(bounds);
}
google.maps.event.addListener(marker, "click", function() { alert("Associated data: " + this.formdateoftrip + ", " + this.findcategory); });
});
}
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>
</head>
<body onLoad="load()">
<form name="findsperlocation" id="findsperlocation">
<p align="left"><label>Location id<br />
</label>
</p>
<div>
<div align="left">
<input name="locationid" type="text" id="locationid" value="2" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Date of Trip<br />
</label>
</p>
<div>
<div align="left">
<input name="dateoftrip" type="text" id="dateoftrip" readonly="readonly"/>
</div>
</div>
<p align="left">
<label></label>
<label>Find Category</label>
</p>
<div>
<div align="left">
<input name="findcategory" type="text" id="findcategory" size="10"readonly="readonly"/>
</div>
</div>
</form>
<div id="map"></div>
</script>
</body>
</html>
CODE SNIPPET
var marker = new google.maps.Marker({
map: map,
position: point,
title: 'Click to view details',
icon: icon.icon,
shadow: icon.shadow,
formdateoftrip: "dateoftrip",
formfindcategory: "findcategory",
formfindname: "findname",
formfinddescription: "finddescription",
formpasref: "pasref",
formfindimage: "findimage",
formadditionalcomments: "additionalcomments"
});
bounds.extend(point);
map.fitBounds(bounds);
}
google.maps.event.addListener(marker, "click", function() {
document.getElementById('dateoftrip').value = this.formdateoftrip;
document.getElementById('findcategory').value = this.formfindcategory;
document.getElementById('findname').value = this.formfindname
});
You can store additional data in your marker just by adding new fields like this:
var marker = new google.maps.Marker(
{
map : map,
position : point,
title : 'Click to view details',
icon : icon.icon,
shadow : icon.shadow,
myVariable1 : "some data from xml",
myVariable2 : "some other data"
});
Then all you have to do is register onClick event for the marker and put it's data into the form.
google.maps.event.addListener(marker, "click", function()
{
alert("Associated data: " + this.myVariable1 + ", " + myVariable2);
});
// Edit:
Obviously the code above only shows how to retrieve data from the marker - it was just an example. Putting your data from JavaScript into the form is a 2 step process. The first thing you have to do is to give every field you want to fill an unique id via "id" attribute. You've already done it. Then all you have to do is put following code in the onClick event (instead of alert() in the sample above):
document.getElementById('formdateoftrip').value = this.formdateoftrip;
// repeat it for other fields here
Good luck ;)
// Another edit:
I didn't notice you've put google.maps.event.addListener in wrong place. The reason it works for only one marker is you've put it outside your "for" loop which creates the markers. It has to be inside, right after the "map.fitBounds(bounds);" but before "}", so move it one line up.
The second problem lies in passing the data in the marker. If you want to reference variables, you can't put them in quotes. You use quotes to write strings.
Replace:
formdateoftrip: "dateoftrip",
formfindcategory: "findcategory",
...
Into:
formdateoftrip: dateoftrip,
formfindcategory: findcategory,
// fix the others below too