upload image using javascript and xajax to MySql Blob - xajax

I want to upload images to database, but I dont know how to receive this file.
//html
<input type="text" id="txtName">
<input type="file" id="image" onchange="sendImage()">
//Javascript
function sendImage()
{
var name = $('#txtName').val();
var image = $('#image').val(); //is this the way to send the image?
xajax_SaveImage(name, image);
}
//xajax
//with string I dont have problems for receive, but how receive I the image?
function SaveImage($name, $image)
{
//How here I convert the image to binary for to save in Mysql
}

You can do this: base64 is the image data, upload that data to database
File.prototype.convertToBase64 = function(callback){
var reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result)
};
reader.onerror = function(e) {
callback(null, e);
};
reader.readAsDataURL(this);
};
$("#image").on('change',function(){
var selectedFile = this.files[0];
if (!selectedFile.name.match(/.(jpg|jpeg|png|gif)$/i)) {
}
else {
selectedFile.convertToBase64(function(base64){
//base64 is the base64 value of the image, use this to send to database...
})
}
});
Code snippet example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="image">
<script>
File.prototype.convertToBase64 = function(callback){
var reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result)
};
reader.onerror = function(e) {
callback(null, e);
};
reader.readAsDataURL(this);
};
$("#image").on('change',function(){
var selectedFile = this.files[0];
if (!selectedFile.name.match(/.(jpg|jpeg|png|gif)$/i)) {
}
else {
selectedFile.convertToBase64(function(base64){
console.log(base64);
})
}
});
</script>

In your template (smarty)
<div id="imageplaceholder" class="left shadow"><p>Place<br />Image<br />here.<br />(drag&drop)</p></div>
<div id="image">
<div id="imageborder" class="left shadow">{if $persondata.imagesize gt 0}<img src="getimage.php?h={$smarty.session.verify}&id={$persondata.id}" />{/if}</div>
</div><div id="imagetools" class="left">
<div id="imagehelp" class="imagetool help radius3 shadow"></div>
<div id="imagenew" class="imagetool new radius3 shadow"></div>
<div id="imagezoomin" class="imagetool zoomin radius3 shadow"></div>
<div id="imagezoomout" class="imagetool zoomout radius3 shadow"></div>
<div id="imageok" class="imagetool ok radius3 shadow"></div>
</div>
js part uses filedrop.
FileDrop JavaScript classes | by Proger_XP https://github.com/ProgerXP/FileDrop
$('#imageplaceholder').filedrop({
// The name of the $_FILES entry:
paramname:'pic',
url: '/img_file.php', //this is the PHP file used for processing
allowedfiletypes: ['image/jpeg','image/png','image/gif'],
uploadFinished:function(i,file,response){
// remove placeholder
// add Image
// $.data(file).addClass('done');
// response is the JSON object that img_file.php returns
$('#imageplaceholder').hide();
loadImage(file);
$('#image').show();
$('#imagetools .help').show();
$('#imagetools .zoomin').show();
$('#imagetools .zoomout').show();
$('#imagetools .ok').show();
$('#imagetools .ok').click(function(){
var img = $('#imageborder').find('img');
var offset = img.offset();
var pos = $('#imageborder').position();
offset.top = pos.top - offset.top;
offset.left = pos.left - offset.left;
var name = $('#imageborder').attr('name');
var scale = $('#imageborder').attr('scale');
var id = $('input[name=user_id]').val();
var hash = $('#hash').val();
var ret = xajax_settings_action({ xjxfun: 'settings_action' }, { parameters: ['saveimage',hash,id,name,offset,scale] }, { mode: 'synchronous' });
if(ret != 0)
{
$('#imagetools .help').hide();
$('#imagetools .zoomin').hide();
$('#imagetools .zoomout').hide();
$('#imagetools .ok').hide();
$('#imagetools .cancel').removeClass('cancel').addClass('new');
}
});
},
rename: function(name) {
// name in string format
// must return alternate name as string
var date = new Date();
// get file type
var typ = name.split('.',2);
// buffer name for save response
$('#imageborder').attr('name',date.getTime() + "." + typ[1]);
return date.getTime() + "." + typ[1];
},
// Called before each upload is started
beforeEach: function(file){
if(!file.type.match(/^image\//)){
jAlert('Only images are allowed!');
// Returning false will cause the
// file to be rejected
return false;
}
},
});
img_file.php
<?php
// Set the directory where files will be saved
$upload_dir = '/tmp/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if( move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']) ){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
I use simpleimage.php from Simon Jarvis to scale and crop the image.
private function save_FileDB($id,$name,$pos,$scale)
{
$upload_dir = "/tmp/";
$response = new xajaxResponse();
$userid = $_SESSION['userid'];
$binFile = $upload_dir.$name;
if (isset($binFile) && $binFile != "none") {
$simage = new SimpleImage();
$simage->load($binFile);
$simage->scale($scale*100);
$simage->crop($pos[left],$pos[top],175,200);
$simage->save($binFile);
$binFile_size = filesize($binFile);
$ext = explode('.', $name);
$ext = strtolower( array_pop($ext) );
switch($ext){
case 'jpg': $binFile_type = 'image/jpeg'; break;
case 'png': $binFile_type = 'image/png'; break;
case 'gif': $binFile_type = 'image/gif'; break;
}
$data = addslashes(fread(fopen($binFile, "r"), $binFile_size ));
$qs = "update persondata set image='$data', imagetype='$binFile_type', imagesize='$binFile_size' where id=$id";
$ret = $this->exec_query($qs);
unlink($binFile);
$response->setReturnValue("1");
return $response;
}
$response->setReturnValue("0");
return $response;
}

Related

How to load/configure IBM Daeja ViewONE in html?

All my requirement is to load daeja docviewer in html and running it using jsp file in jboss server
I have tried to load/configure IBM Daeja ViewONE using Html.I have included necessary jars and license files but it is not loading. Please help in resolving this and check i need to add/remove any thing to get this running
Jars added
Html :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script language="javascript" type="text/javascript" src="viewone.js"></script>
<title>User Data</title>
</head>
<body>
<div>
<Object class="com.ibm.dv.client.Viewer" id="viewone" width="100%" height="100%" name="viewone">
<param name="trace" value="true">
<param name="tracenet" value="true">
<param name="tracefilter" value="true">
</Object>
</div>
</body>
</html>
``
viewone.js
function ViewOneBootstrap() { alert('1ds1');
this.logMessages = new Array();
this.debugMessages = new Array();
this.clientids = new Array();
this.codebase = null;
this.lastFocussed = null;
this.objectTag = "com.ibm.dv.client.Viewer";
this.instanceId = 1;
//document content clipboard
this.clipboard = new ViewOneClipboard();
this.getInstanceId = function() {
return "" + this.instanceId++;
}
this.addMessage = function(message) {
this.logMessages.push(message);
this.log(message)
};
this.clearMessages = function() {
this.logMessages = new Array();
};
this.log = function(message) {
if (this.debugMessages.length >= 100)
this.debugMessages.shift();
this.debugMessages.push(message);
if (window.console) {
if (window.console.debug)
window.console.debug(message);
else if (window.console.log)
window.console.log(message);
}
};
this.getHead = function() {
var headElem = null;
var oHead = document.getElementsByTagName('head');
if (oHead == null || oHead.length == 0) {
headElem = document.createElement();
document.appendChild(headElem);
} else {
headElem = oHead[0];
}
return headElem;
};
this.includeJS = function(sId, fileUrl, source) {
viewoneLoader.addMessage("Attaching script " + sId
+ (source == null ? "" : (" length=" + source.length)));
if ((source != null) && (!document.getElementById(sId))) {
var oHead = viewoneLoader.getHead();
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.id = sId;
oScript.defer = "true";
if (source == null) {
oScript.src = fileUrl;
} else {
oScript.text = source;
}
viewoneLoader.getHead().appendChild(oScript);
viewoneLoader.addMessage("Script attached");
}
};
var addMessage = this.addMessage;
this.addMessage('ViewOneBootstrap:init<>');
this.showMessages = function() {
var messages = "";
for (var i = 0; i < this.logMessages.length; i++) {
messages += this.logMessages[i];
messages += "\n";
}
alert(messages);
};
this.getHttpRequest = function() {
if (window.XMLHttpRequest)
return new XMLHttpRequest();
if (window.ActiveXObject)
return new ActiveXObject("MsXml2.XmlHttp");
};
this.loadScript = function(sId, url, postData) {
this.codebase = url;
this.postData = postData;
this.addMessage('ViewOneBootstrap.loadScript: ' + url);
var oXmlHttp = this.getHttpRequest();
var scriptLoad = this.includeJS;
var loadFailed = this.loadError;
oXmlHttp.onreadystatechange = function() {
if (oXmlHttp.readyState == 4) {
if (oXmlHttp.status == 200 || oXmlHttp.status == 304) {
viewoneLoader.addMessage("Script downloaded");
scriptLoad(sId, url, oXmlHttp.responseText);
} else {
var isCrossDomain = true;
if (url.indexOf("http://") != 0 && url.indexOf("https://") != 0)
isCrossDomain = false;
// Can't be cross domain unless the URL starts http: or https:
else if (url.indexOf("https:") == 0 && window.location.protocol != "https:")
isCrossDomain = false;
else if (url.indexOf("http:") == 0 && window.location.protocol != "http:")
isCrossDomain = false;
else {
var url2 = url.replace(/^https?:\/\//, "");
var match = url2.match(/^[^\/]+/);
if (match) {
var domain = match[0];
if (window.location.host == domain)
isCrossDomain = false;
}
}
if (isCrossDomain && oXmlHttp.status == 0) {
loadFailed("Cannot load ViewONE.\n"
+ "Likely reasons include:\n"
+ "- Cross domain resource loading is not supported by this browser\n"
+ "- Cross domain resource loading is not configured correctly on the server\n"
+ "- There was a temporary network issue when loading ViewONE\n"
+ "- This web browser has incorrectly cached some data (please empty the cache)");
} else {alert('error 2');
viewoneLoader.addMessage('XML request error: '
+ oXmlHttp.statusText + ' (' + oXmlHttp.status
+ ')');
viewoneLoader.showMessages();
}
}
}
};
oXmlHttp.open('GET', url, true);
if (oXmlHttp.setRequestHeader)
oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oXmlHttp.send(null);
};
this.includeJS = function(sId, fileUrl, source) {
viewoneLoader.addMessage("Attaching script " + sId
+ (source == null ? "" : (" length=" + source.length)));
if (!(source == null && fileUrl == null)
&& (!document.getElementById(sId))) {
var oHead = viewoneLoader.getHead();
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.id = sId;
oScript.defer = "true";
if (source == null) {
oScript.src = fileUrl;
} else {
oScript.text = source;
}
oHead.appendChild(oScript);
viewoneLoader.addMessage("Script attached");
}
};
this.addMetaTag = function(name, content) {
this.addMessage('ViewOneBootstrap.addMetaTag');
var oHead = this.getHead();
var mTag = document.createElement("meta");
mTag.name = name;
mTag.content = content;
oHead.appendChild(mTag);
};
this.loadCompleted = function() {
this.addMessage("ViewOneBootstrap.loadCompleted: viewer ready to start");
if (window.notifyViewONECodeInit)
{
window.notifyViewONECodeInit();
}
};
this.loadError = function(message) {
addMessage(message);
if (window.deinitPercentage) {
window.deinitPercentage();
addMessage("Percentage display removed");
}
if (window.showViewoneLoadError)
window.showViewoneLoadError(message);
else
alert(message);
}
}
function ViewOneClipboard() {
this.content = null;
this.putContent = function(jsonBlob)
{
//viewoneLoader.log("added to clipboard: " + jsonBlob);
this.content = jsonBlob;
}
this.getContent = function()
{
//viewoneLoader.log("retrieved from clipboard: "+ this.content);
return this.content;
}
}
var viewoneLoader = new ViewOneBootstrap();
//viewoneLoader.addMetaTag('viewone_ajax::gwt:property', 'baseUrl=filenet/v1files/?v=9001&op=resource&file=');
//viewoneLoader.loadScript('viewoneLoader', 'filenet/v1files/?v=9001&op=resource&file=viewone.cache.js', '');
viewoneLoader.com_viewone_instance = '1';
viewoneLoader.com_viewone_instancel = {"start":"","end":"","num":"", "modInf": [{"type":"2"}, {"type":"3"}, {"type":"4"}, {"type":"5"}, {"type":"6"}, {"type":"8"}, {"type":"G"}, {"type":"I"}, {"type":"M"}],"trial":false,"company":"","country":"","support":false,"contact":"","rProduct":"","rCompany":"","rEmail":"","rSite":"","rAllowIgnorePro":false,"testBuild":false,"legacyFeatures":false};
viewoneLoader.loadingMessage = 'IBM Daeja ViewONE Virtual 5.0.3';
viewoneLoader.version = "9001";
viewoneLoader.displayversion = "5.0.3";
viewoneLoader.fulldisplayversion = "5.0.3 iFix 1";
viewoneLoader.acceptLanguages = ["en-US","en"];
If you remove DIV tags around Daeja object, the page will get loaded.
If you want to keep the DIV, you need to change width and height value from percentage to absolute px value. Otherwise it won't work. Don't know why and really don't like the way it is.

angular4 upload image and pass to server and save into database(express and mongoose, mongodb)

Is there anyone knows how to upload an image within Angular 4 environment, then sending this data to the backend as express server, and using mongoose to store into mongodb? if anyone knows, please post the answer. Thank
File input
{{imgfile.errors | json}}
<div class="alert alert-danger"
*ngIf="size >= 300000">
<strong>
Can't upload this image. check image size!!!
</strong>
</div>
Script
onFileChange(event) {
let reader = new FileReader();
if(event.target.files && event.target.files.length > 0) {
console.log(event.target.files)
let file = event.target.files[0];enter code here
this.size = file.size;
console.log(file.size);
if (file.size <= 300000) {
this.picSize = true;
}
reader.onload = () => {
this.new_food.image = reader.result;
};
reader.readAsDataURL(file);
}
}
onFileChange(event) {
let reader = new FileReader();
if(event.target.files && event.target.files.length > 0) {
console.log(event.target.files)
let file = event.target.files[0];enter code here
this.size = file.size;
console.log(file.size);
if (file.size <= 300000) {
this.picSize = true;
}
reader.onload = () => {
this.new_food.image = reader.result;
};
reader.readAsDataURL(file);
}
}

Extending Dynamic-forms from angular2 cookbook to be able to have arrays

I have tried to extend the Dynamic-Forms app from angular 2 cookbook so I can have an array of multiple fields. I have been able to show the fields, but when I'm filling the form, I'm getting just the last element of the array filled.
Hier is my plunker with that state of the app:
//question-array.ts
import { QuestionBase } from './question-base';
export class ArrayQuestion extends QuestionBase<string> {
controlType = 'array';
options:{childe:FormElement<string>}[] = [];
constructor(options:{} = {}){
super(options);
this.options = options['options'] || [];
}
}
//question-control.service.ts
...
toFormGroup(formelements: QuestionBase<any>[] ) {
let group:any = {};
formelements.forEach(element => {
console.log("+element",element);
if(element.controlType === "array"){
let arr:any[] = [];
let locobj = {};
element["options"].forEach((option:any) => {
option["element"].forEach((e:any) =>{
locobj[e.key] = new FormControl(e.value || '');
});
arr.push(new FormGroup(locobj))
});
group[element.key] = new FormArray(arr);
}else{
group[element.key] = element.required ? new FormControl(element.value || '', Validators.required)
: new FormControl(element.value || '');
}
});
return new FormGroup(group);
}
//dynamic-form-question.component.html
...
<div *ngSwitchCase="'array'" [formArrayName]="question.key">
<div *ngFor="let item of question.options; let i=index" [formGroupName]="i" >
<div *ngFor="let element of item.element">
<div *ngIf="element.controlType === 'textbox'" >
<label>{{element.label}}</label>
<input [formControlName]="element.key" [id]="element.key" [type]="element.type" />
</div>
<div *ngIf="element.controlType === 'dropdown'" >
<label>{{item.label}}</label>
<select [id]="element.key" [formControlName]="element.key">
<option *ngFor="let opt of element.options" [value]="opt.key">{{opt.value}}</option>
</select>
</div>
</div>
</div>
</div>
...
http://plnkr.co/edit/DZ05fO
Best regard,
Shefki
I found the bug, the problem was that I was passing the same reference in the form group her is what i changed:
//question-control.service.ts
toFormGroup(formelements: QuestionBase[] ) {
let group:any = {};
formelements.forEach(element => {
if(element.controlType === "array"){
let arr:any[] = [];
let locobj = {};
element["options"].forEach((option:any) => {
option["element"].forEach((e:any) =>{
locobj[e.key] = e.value || '';
});
arr.push(new FormGroup(this.getFormControlObject(locobj)));
});
group[element.key] = new FormArray(arr);
}else{
group[element.key] = element.required ? new FormControl(element.value || '', Validators.required)
: new FormControl(element.value || '');
}
});
return new FormGroup(group);
}
private getFormControlObject(keys){
let retobj = {};
Object.keys(keys).forEach(function(key) {
retobj[key] = new FormControl(keys[key]);
});
return retobj;
}
Hier is a working plunker
http://plnkr.co/edit/4IMKdLKE51n41jzYY8sU

how to disable background-color input fields

I am using a form validation with javascript.
When submitting, the background-color of those input fields which are not valid changes to red color. When filling up this field and typing into another input field, the red background-color of the former field should go away. This is at the moment not the case. It only disappears when submitting again. How can I make this possible that the bg color changes back to normal when typing into another field?
// Return true if the input value is not empty
function isNotEmpty(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.length !== 0); // boolean
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
/* If "isValid" is false, print the errorMsg; else, reset to normal display.
* The errorMsg shall be displayed on errorElement if it exists;
* otherwise via an alert().
*/
function showMessage(isValid, inputElement, errorMsg, errorElement) {
if (!isValid) {
// Put up error message on errorElement or via alert()
if (errorElement !== null) {
errorElement.innerHTML = errorMsg;
} else {
alert(errorMsg);
}
// Change "class" of inputElement, so that CSS displays differently
if (inputElement !== null) {
inputElement.className = "error";
inputElement.focus();
}
} else {
// Reset to normal display
if (errorElement !== null) {
errorElement.innerHTML = "";
}
if (inputElement !== null) {
inputElement.className = "";
}
}
}
The form:
<td>Name<span class="red">*</span></td>
<td><input type="text" id="name" name="firstname"/></td>
<p id="nameError" class="red"> </p>
The submit:
<input type="submit" value="SEND" id="submit"/>
Css:
input.error { /* for the error input text fields */
background-color: #fbc0c0;
}
Update:
I tried this but it seems not to work:
function checkFilled() {
var inputVal = document.querySelectorAll("#offerteFirstname, #offerteLastname, #offertePhone, #offertePoster, #offerteStreet").value;
if (inputVal == "") {
document.querySelectorAll("#offerteFirstname, #offerteLastname, #offertePhone, #offertePoster, #offerteStreet").style.backgroundColor = "red";
}
else{
document.querySelectorAll("#offerteFirstname, #offerteLastname, #offertePhone, #offertePoster, #offerteStreet").style.backgroundColor = "white";
}
}
checkFilled();
here example of it
<input type="text" id="subEmail" onchange="checkFilled();"/>
and now you can JavaScript on input
function checkFilled() {
var inputVal = document.getElementById("subEmail").value;
if (inputVal == "") {
document.getElementById("subEmail").style.backgroundColor = "white";
}
else{
document.getElementById("subEmail").style.backgroundColor = "red";
}
}
checkFilled();
here working demo
Try
$(formElement).on('keyup','input.error', function(){
if(<values changed>){
$(this).removeClass('error');
}
});

Google Maps API GeoLocation not working for mobile

I'm not really sure why the GeoLocation works on my PC, but not my iPhone ... I've got sensor=true within the script call to the API, but apart from that, I'm at a loss. Here's the entire script:
<div id="info"></div>
<div id="map_canvas" style="width:908px; height:420px"></div>
<input type="text" id="addressInput" size="10"/>
<select id="radiusSelect">
<option value="5" selected>5mi</option>
<option value="15" selected>15mi</option>
<option value="25" selected>25mi</option>
<option value="100">100mi</option>
<option value="200">200mi</option>
<option value="4000">4000mi</option>
</select>
<input type="button" value="Search" onclick="searchLocations();">
<div><select id="locationSelect" style="width:100%;visibility:hidden"></select></div>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCe49sI29q0AVNo9iVvQ-lDlDwZpFZuA4o&sensor=true"></script>
<script type="text/javascript" src="http://gmaps-samples-v3.googlecode.com/svn/trunk/geolocate/geometa.js"></script>
<script type="text/javascript">
var map;
var markers = [];
var infoWindow;
var locationSelect;
function load() {
map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none") {
google.maps.event.trigger(markers[markerNum], 'click');
}
};
// geolocation
prepareGeolocation();
doGeolocation();
}
function doGeolocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(positionSuccess, positionError);
} else {
positionError(-1);
}
}
function positionError(err) {
var msg;
switch(err.code) {
case err.UNKNOWN_ERROR:
msg = "Unable to find your location";
break;
case err.PERMISSION_DENINED:
msg = "Permission denied in finding your location";
break;
case err.POSITION_UNAVAILABLE:
msg = "Your location is currently unknown";
break;
case err.BREAK:
msg = "Attempt to find location took too long";
break;
default:
msg = "Location detection not supported in browser";
}
document.getElementById('info').innerHTML = msg;
}
function positionSuccess(position) {
// Centre the map on the new location
var coords = position.coords || position.coordinate || position;
var latLng = new google.maps.LatLng(coords.latitude, coords.longitude);
map.setCenter(latLng);
map.setZoom(15);
var marker = new google.maps.Marker({
map: map,
position: latLng,
title: 'Why, there you are!'
});
document.getElementById('info').innerHTML = 'Looking for <b>' +
coords.latitude + ', ' + coords.longitude + '</b>...';
// And reverse geocode.
(new google.maps.Geocoder()).geocode({latLng: latLng}, function(resp) {
var place = "You're around here somewhere!";
if (resp[0]) {
var bits = [];
for (var i = 0, I = resp[0].address_components.length; i < I; ++i) {
var component = resp[0].address_components[i];
if (contains(component.types, 'political')) {
bits.push('<b>' + component.long_name + '</b>');
}
}
if (bits.length) {
place = bits.join(' > ');
}
marker.setTitle(resp[0].formatted_address);
}
document.getElementById('info').innerHTML = place;
});
}
function contains(array, item) {
for (var i = 0, I = array.length; i < I; ++i) {
if (array[i] == item) return true;
}
return false;
}
function searchLocations() {
console.log("searching locations...");
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
//infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
locationSelect.style.visibility = "visible";
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
/* var searchUrl = 'phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius; */
var searchUrl = 'http://dev-imac.local/phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
console.log(searchUrl);
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
window.onload = load();
</script>
First of all,
mapTypeId: 'roadmap',
should be:
mapTypeId: google.maps.MapTypeId.ROADMAP,
but that should cause it to fail in your PC as well.
Other than that, your <script> section should be in the <head> section of the document and not in the <body>. Maybe the iPhone browser is more strict about this than the browser on your PC. What browser(s) are you using in each system? (I'm guessing you're using IE on the PC. Have you tried other browsers?)