Search Results

Search found 38 results on 2 pages for 'htmltext'.

Page 2/2 | < Previous Page | 1 2 

  • Applying styles for custom TextArea in ActionScript 3

    - by Vijay Dev
    I have the following code to create and apply a few styles for a custom TextArea in ActionScript 3. public class MyCustomTextArea extends TextArea { override protected function createChildren():void { super.createChildren(); this.styleSheet.setStyle("sup", { display: "inline", fontFamily: "ArialSup", fontSize:"12"}); this.styleSheet.setStyle("sub", { display: "inline", fontFamily: "ArialSub", fontSize:"12"}); this.setStyle("fontFamily", "Arial"); } } I have two problems with this code. this.styleSheet is always null when I create an instance of the class. If this.styleSheet is initialized to new StyleSheet() to avoid this issue, then the TextArea instance does not seem to recognize any of the HTML tags that can be used with the htmlText property. Can anyone help in fixing these two issues? Thanks.

    Read the article

  • How to Identify the website's content language

    - by Ajay
    I am developing a website to crawl the other website content in ASP.NET . I am able to get the content correctly but how can I identify which language is used based on that content. I used following code. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(TextBox1.Text ); request.UserAgent = "A .NET Web Crawler"; WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string htmlText = reader.ReadToEnd();

    Read the article

  • using html text in as3

    - by vincent
    Hello, i'm having a bit of a question, I have some newspost from my database. But there are tags in it and some tags aswell. My questiion is how i should go about it to get the newspost showing as it should be. The images should get shown instead of the tags etc. I know i'll have to work with a loader to use the images but how would as3 recognize them? Is there anyway i could use htmltext or something so as3 knows automaticly where the imagetags are? Also, if i add the image would it be possible to wrap the text around it? So i dont have an empty space next to the image?

    Read the article

  • Problem with displaying my Image..

    - by Josh
    Here is my full problem so if anyone has any ideas or can offer some help, please let me know. I have a Website that will generate a Report and this Report takes some time to create. There is a MyReport.ASPX file that has a form1, Image1, and a ReportViewer control. There is also a MyReport.cs file that has C# code to generated a HTMLText string that the ReportViewer control will display. When I pull the Website up in the browser, the MyReport.cs file creates the Report before MyReport.ASPX ever gets called so my Image1 (which I need to display while the Report is being created) never gets displayed until AFTER the Report is created and displayed. What do you suggest I do here? If I did not supply enough information, please let me know what else you need to know and I will gladly post it. Thanks,

    Read the article

  • Firefox DOMParser problem

    - by Michael
    For some reason DOMParser is adding some additional #text elements for each newline \n for this url http://rt.com/Root.rss ...as well as many other RSS I've tried. I checked cnn/bbc feeds, they don't have newlines and dom parser handling them nicely. So I have to add the following before parsing it var xmlText = htmlText.replace(/\n[ ]*/g, ""); var xmlDoc = parser.parseFromString(xmlText, "text/xml"); Server is returning text/xml. var channel = xmlDoc.documentElement.childNodes[0]; this returning \n without my code above and channel with correction.

    Read the article

  • Retrieve parent node from selection (range) in Gecko and Webkit

    - by Jason
    I am trying to add an attribute when using a wysiwyg editor that uses "createLink" command. I thought it would be trivial to get back the node that is created after the browse executes that command. Turns out, I am only able to grab this newly created node in IE. Any ideas? The following code demonstrates the issue (debug logs at bottom show different output in each browser): var getSelectedHTML = function() { if ($.browser.msie) { return this.getRange().htmlText; } else { var elem = this.getRange().cloneContents(); return $("<p/>").append($(elem)).html(); } }; var getSelection = function() { if ($.browser.msie) { return this.editor.selection; } else { return this.iframe[0].contentDocument.defaultView.getSelection(); } }; var getRange = function() { var s = this.getSelection(); return (s.getRangeAt) ? s.getRangeAt(0) : s.createRange(); }; var getSelectedNode = function() { var range = this.getRange(); var parent = range.commonAncestorContainer ? range.commonAncestorContainer : range.parentElement ? range.parentElement(): range.item(0); return parent; }; // **** INSIDE SOME EVENT HANDLER **** if ($.browser.msie) { this.ec("createLink", true); } else { this.ec("createLink", false, prompt("Link URL:", "http://")); } var linkNode = $(this.getSelectedNode()); linkNode.attr("rel", "external"); $.log(linkNode.get(0).tagName); // Gecko: "body" // IE: "a" // Webkit: "undefined" $.log(this.getSelectedHTML()); // Gecko: "<a href="http://site.com">foo</a>" // IE: "<A href="http://site.com" rel=external>foo</A>" // Webkit: "foo" $.log(this.getSelection()); // Gecko: "foo" // IE: [object Selection] // Webkit: "foo" Thanks for any help on this, I've scoured related questions on SO with no success!

    Read the article

  • Flash AS3: How to Make scroll bar react to dynamic textfield movement?

    - by HeroicNate
    I've been looking for a tutorial and answer to this for a while but can't find what I'm looking for. I am loading html text into a dynamic textfield, and I have a scrollbar controlling the scroll using the code below. What I want to do is also add scroll up/down buttons and have the scroll bar move in relation to the text scroll. I was just going to use "tracklistingtext.scrollV -- " for the scroll buttons, but right now the scroll bar doesn't recognize the text movement. What do I need to do to get the scroll bar to listen to the text scroll position? var listTextreq:URLRequest=new URLRequest("tracklist.txt"); var listTextLoader:URLLoader = new URLLoader(); var bounds:Rectangle=new Rectangle(scrollMC.x,scrollMC.y,0,300); var scrolling:Boolean=false; function fileLoaded(event:Event):void { tracklistingtext.htmlText=listTextLoader.data; tracklistingtext.multiline=true; tracklistingtext.wordWrap=true; scrollMC.addEventListener(MouseEvent.MOUSE_DOWN, startScroll); stage.addEventListener(MouseEvent.MOUSE_UP, stopScroll); addEventListener (Event.ENTER_FRAME, enterHandler); } listTextLoader.addEventListener(Event.COMPLETE, fileLoaded); listTextLoader.load(listTextreq); function startScroll(e:Event):void { scrolling=true; scrollMC.startDrag(false,bounds); } function stopScroll(e:Event):void { scrolling=false; scrollMC.stopDrag(); } function enterHandler (e:Event):void { if (scrolling == true) { tracklistingtext.scrollV = Math.round(((scrollMC.y - bounds.y)/300)*tracklistingtext.maxScrollV); } } Any help is greatly appreciated.

    Read the article

  • Silverstripe: outputting DataObjectManager in template include

    - by Fraser
    I have followed the tutorial here http://doc.silverstripe.org/old/modules:dataobjectmanager to create a dataobjectmanager in my CMS. It's all working perfectly there however I am having an issue getting it to output in the template. My code is as follows <?php class InfoArea extends DataObject{ static $db = array( 'Title' => 'Varchar(255)', 'Content' => 'HTMLText' ); static $has_one = array( 'ResortPage' => 'ResortPage' ); public function getCMSFields_forPopup(){ return new FieldSet( new TextField('Title'), new SimpleTinyMCEField('Content') ); } } ResortPage.php ....... static $has_many = array ( "InfoAreas" => "InfoArea" ); ....... $fields->addFieldToTab("Root.Content.AdditionalInformation", new DataObjectManager( $this, 'InfoAreas', 'InfoArea', array('Title' => 'Title','Content'=>'Content'), 'getCMSFields_forPopup' )); ........ I have a template "ResortPage.ss" which has an include "ResortInfo.ss". It is from within this include file that I need to output the DataObject. I have tried the below but it doesn't output anything <% control InfoArea %> $Title $Content <% end_control %> What am I doing wrong here? Thanks

    Read the article

  • actionscript find and convert text to url

    - by gravesit
    I have this script that grabs a twitter feed and displays in a little widget. What I want to do is look at the text for a url and convert that url to a link. public class Main extends MovieClip { private var twitterXML:XML; // This holds the xml data public function Main() { // This is Untold Entertainment's Twitter id. Did you grab yours? var myTwitterID= "username"; // Fire the loadTwitterXML method, passing it the url to your Twitter info: loadTwitterXML("http://twitter.com/statuses/user_timeline/" + myTwitterID + ".xml"); } private function loadTwitterXML(URL:String):void { var urlLoader:URLLoader = new URLLoader(); // When all the junk has been pulled in from the url, we'll fire finishedLoadingXML: urlLoader.addEventListener(Event.COMPLETE, finishLoadingXML); urlLoader.load(new URLRequest(URL)); } private function finishLoadingXML(e:Event = null):void { // All the junk has been pulled in from the xml! Hooray! // Remove the eventListener as a bit of housecleaning: e.target.removeEventListener(Event.COMPLETE, finishLoadingXML); // Populate the xml object with the xml data: twitterXML = new XML(e.target.data); showTwitterStatus(); } private function addTextToField(text:String,field:TextField):void{ /*Regular expressions for replacement, g: replace all, i: no lower/upper case difference Finds all strings starting with "http://", followed by any number of characters niether space nor new line.*/ var reg:RegExp=/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; //Replaces Note: "$&" stands for the replaced string. text.replace(reg,"<a href=\"$&\">$&</a>"); field.htmlText=text; } private function showTwitterStatus():void { // Uncomment this line if you want to see all the fun stuff Twitter sends you: //trace(twitterXML); // Prep the text field to hold our latest Twitter update: twitter_txt.wordWrap = true; twitter_txt.autoSize = TextFieldAutoSize.LEFT; // Populate the text field with the first element in the status.text nodes: addTextToField(twitterXML.status.text[0], twitter_txt); }

    Read the article

  • array data taking XML value is not taking css value in as3

    - by Sagar S. Ranpise
    I have xml structure all data comes here inside CDATA I am using css file in it to format text and classes are mentioned in xml Below is the code which shows data but does not format with CSS. Thanks in advance! var myXML:XML = new XML(); var myURLLoader:URLLoader = new URLLoader(); var myURLRequest:URLRequest = new URLRequest("test.xml"); myURLLoader.load(myURLRequest); //////////////For CSS/////////////// var myCSS:StyleSheet = new StyleSheet(); var myCSSURLLoader:URLLoader = new URLLoader(); var myCSSURLRequest:URLRequest = new URLRequest("test.css"); myCSSURLLoader.load(myCSSURLRequest); myCSSURLLoader.addEventListener(Event.COMPLETE,processXML); var i:int; var textHeight:int = 0; var textPadding:int = 10; var txtName:TextField = new TextField(); var myMov:MovieClip = new MovieClip(); var myMovGroup:MovieClip = new MovieClip(); var myArray:Array = new Array(); function processXML(e:Event):void { myXML = new XML(myURLLoader.data); trace(myXML.person.length()); var total:int = myXML.person.length(); trace("total" + total); for(i=0; i<total; i++) { myArray.push({name: myXML.person[i].name.toString()}); trace(myArray[i].name); } processCSS(); } function processCSS():void { myCSS.parseCSS(myCSSURLLoader.data); for(i=0; i<myXML.person.length(); i++) { myMov.addChild(textConvertion(myArray[i].name)); myMov.y = textHeight; textHeight += myMov.height + textPadding; trace("Text: "+myXML.person[i].name); myMovGroup.addChild(myMov); } this.addChild(myMovGroup); } function textConvertion(textConverted:String) { var tc:TextField = new TextField(); tc.htmlText = textConverted; tc.multiline = true; tc.wordWrap = true; tc.autoSize = TextFieldAutoSize.LEFT; tc.selectable = true; tc.y = textHeight; textHeight += tc.height + textPadding; tc.styleSheet = myCSS; return tc; }

    Read the article

  • Actionscript multiple file upload, with parameter passing is not working

    - by Metropolis
    Hey everyone, First off, I am very bad at flash/actionscript, it is not my main programming language. I have created my own file upload flash app that has been working great for me up until this point. It uses PHP to upload the files and sends back a status message which gets displayed in a status box to the user. Now I have run into a situation where I need the HTML to pass a parameter to the Actionscript, and then to the PHP file using POST. I have tried to set this up just like adobe has it on http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_7.html without success. Here is my Actionscript code import fl.controls.TextArea; //Set filters var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png"); var textTypes:FileFilter = new FileFilter("Documents (*.txt, *.rtf, *.pdf, *.doc)", "*.txt; *.rtf; *.pdf; *.doc"); var allTypes:Array = new Array(textTypes, imageTypes); var fileRefList:FileReferenceList = new FileReferenceList(); //Add event listeners for its various fileRefList functions below upload_buttn.addEventListener(MouseEvent.CLICK, browseBox); fileRefList.addEventListener(Event.SELECT, selectHandler); function browseBox(event:MouseEvent):void { fileRefList.browse(allTypes); } function selectHandler(event:Event):void { var phpRequest:URLRequest = new URLRequest("ajax/upload.ajax.php"); var flashVars:URLVariables = objectToURLVariables(this.root.loaderInfo); phpRequest.method = URLRequestMethod.POST; phpRequest.data = flashVars; var file:FileReference; var files:FileReferenceList = FileReferenceList(event.target); var selectedFileArray:Array = files.fileList; var listener:Object = new Object(); for (var i:uint = 0; i < selectedFileArray.length; i++) { file = FileReference(selectedFileArray[i]); try { file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, phpResponse); file.upload(phpRequest); } catch (error:Error) { status_txt.text = file.name + " Was not uploaded correctly (" + error.message + ")"; } } } function phpResponse(event:DataEvent):void { var file:FileReference = FileReference(event.target); status_txt.htmlText += event.data; } function objectToURLVariables(parameters:Object):URLVariables { var paramsToSend:URLVariables = new URLVariables(); for(var i:String in parameters) { if(i!=null) { if(parameters[i] is Array) paramsToSend[i] = parameters[i]; else paramsToSend[i] = parameters[i].toString(); } } return paramsToSend; } The flashVars variable is the one that should contain the values from the HTML file. But whenever I run the program and output the variables in the PHP file I receive the following. //Using this command on the PHP page print_r($_POST); //I get this for output Array ( [Filename] => testfile.txt [Upload] => Submit Query ) Its almost like the parameters are getting over written or are just not working at all. Thanks for any help, Metropolis

    Read the article

  • Flex actionscript extending DateChooser, events in calendar

    - by Nemi
    ExtendedDateChooser class is great solution for simple event calendar used in my flex project. You can find it if google for "Adding-Calendar-Event-Entries-to-the-Flex-DateChooser-Component" with a link of updated solution in comments of the post. I posted files below. Problem in that calendar is text events are missing when month is changed. Is there updateCompleted event in Actionscript just like in dateChooser flex component? Like in: <mx:DateChooser id="dc" updateCompleted="goThroughDateChooserCalendarLayoutAndSetEventsInCalendarAgain()"</mx> When scroll event is added, which is available in Actionscript, it gets dispatched but after updateDisplayList() is fired, so didn't manage to answer, why are calendar events erased? Any suggestions, what to add in code, maybe override some function? ExtendedDateChooserClass.mxml <?xml version='1.0' encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:mycomp="cyberslingers.controls.*" layout="absolute" creationComplete="init()"> <mx:Script> <![CDATA[ import cyberslingers.controls.ExtendedDateChooser; import mx.rpc.events.ResultEvent; import mx.rpc.events.FaultEvent; import mx.controls.Alert; public var mycal:ExtendedDateChooser = new ExtendedDateChooser(); // collection to hold date, data and label [Bindable] public var dateCollection:XMLList = new XMLList(); private function init():void { eventList.send(); } private function readCollection(event:ResultEvent):void { dateCollection = event.result.calendarevent; //Position and size the calendar mycal.width = 400; mycal.height = 400; //Add the data from the XML file to the calendar mycal.dateCollection = dateCollection; //Add the calendar to the canvas this.addChild(mycal); } private function readFaultHandler(event:FaultEvent):void { Alert.show(event.fault.message, "Could not load data"); } ]]> </mx:Script> <mx:HTTPService id="eventList" url="data.xml" resultFormat="e4x" result="readCollection(event);" fault="readFaultHandler(event);"/> </mx:Application> ExtendedDateChooser.as package cyberslingers.controls { import flash.events.Event; import flash.events.TextEvent; import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.controls.CalendarLayout; import mx.controls.DateChooser; import mx.core.UITextField; import mx.events.FlexEvent; public class ExtendedDateChooser extends DateChooser { public function ExtendedDateChooser() { super(); this.addEventListener(TextEvent.LINK, linkHandler); this.addEventListener(FlexEvent.CREATION_COMPLETE, addEvents); } //datasource public var dateCollection:XMLList = new XMLList(); //-------------------------------------- // Add events //-------------------------------------- /** * Loop through calendar control and add event links * @param e */ private function addEvents(e:Event):void { // loop through all the calendar children for(var i:uint = 0; i < this.numChildren; i++) { var calendarObj:Object = this.getChildAt(i); // find the CalendarLayout object if(calendarObj.hasOwnProperty("className")) { if(calendarObj.className == "CalendarLayout") { var cal:CalendarLayout = CalendarLayout(calendarObj); // loop through all the CalendarLayout children for(var j:uint = 0; j < cal.numChildren; j++) { var dateLabel:Object = cal.getChildAt(j); // find all UITextFields if(dateLabel.hasOwnProperty("text")) { var day:UITextField = UITextField(dateLabel); var dayHTML:String = day.text; day.selectable = true; day.wordWrap = true; day.multiline = true; day.styleName = "EventLabel"; //TODO: passing date as string is not ideal, tough to validate //Make sure to add one to month since it is zero based var eventArray:Array = dateHelper((this.displayedMonth+1) + "/" + dateLabel.text + "/" + this.displayedYear); if(eventArray.length > 0) { for(var k:uint = 0; k < eventArray.length; k++) { dayHTML += "<br><A HREF='event:" + eventArray[k].data + "' TARGET=''>" + eventArray[k].label + "</A>"; } day.htmlText = dayHTML; } } } } } } } //-------------------------------------- // Events //-------------------------------------- /** * Handle clicking text link * @param e */ private function linkHandler(event:TextEvent):void { // What do we want to do when user clicks an entry? Alert.show("selected: " + event.text); } //-------------------------------------- // Helpers //-------------------------------------- /** * Build array of events for current date * @param string - current date * */ private function dateHelper(renderedDate:String):Array { var result:Array = new Array(); for(var i:uint = 0; i < dateCollection.length(); i++) { if(dateCollection[i].date == renderedDate) { result.push(dateCollection[i]); } } return result; } } } data.xml <?xml version="1.0" encoding="utf-8"?> <rss> <calendarevent> <date>8/22/2009</date> <data>This is a test 1</data> <label>Stephens Test 1</label> </calendarevent> <calendarevent> <date>8/23/2009</date> <data>This is a test 2</data> <label>Stephens Test 2</label> </calendarevent> </rss>

    Read the article

  • how to use 3D map Actionscript class in mxml file for display map.

    - by nemade-vipin
    hello friends, I have created the application in which I have to use 3D map Action Script class in mxml file to display a map in form. that is in tab navigator last tab. My ActionScript 3D map class is(FlyingDirections):- package src.SBTSCoreObject { import src.SBTSCoreObject.JSONDecoder; import com.google.maps.InfoWindowOptions; import com.google.maps.LatLng; import com.google.maps.LatLngBounds; import com.google.maps.Map3D; import com.google.maps.MapEvent; import com.google.maps.MapOptions; import com.google.maps.MapType; import com.google.maps.MapUtil; import com.google.maps.View; import com.google.maps.controls.NavigationControl; import com.google.maps.geom.Attitude; import com.google.maps.interfaces.IPolyline; import com.google.maps.overlays.Marker; import com.google.maps.overlays.MarkerOptions; import com.google.maps.services.Directions; import com.google.maps.services.DirectionsEvent; import com.google.maps.services.Route; import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.filters.DropShadowFilter; import flash.geom.Point; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.utils.Timer; import flash.utils.getTimer; public class FlyingDirections extends Map3D { /** * Panoramio home page. */ private static const PANORAMIO_HOME:String = "http://www.panoramio.com/"; /** * The icon for the car. */ [Embed("assets/car-icon-24px.png")] private static const Car:Class; /** * The Panoramio icon. */ [Embed("assets/iw_panoramio.png")] private static const PanoramioIcon:Class; /** * We animate a zoom in to the start the route before the car starts * to move. This constant sets the time in seconds over which this * zoom occurs. */ private static const LEAD_IN_DURATION:Number = 3; /** * Duration of the trip in seconds. */ private static const TRIP_DURATION:Number = 40; /** * Constants that define the geometry of the Panoramio image markers. */ private static const BORDER_T:Number = 3; private static const BORDER_L:Number = 10; private static const BORDER_R:Number = 10; private static const BORDER_B:Number = 3; private static const GAP_T:Number = 2; private static const GAP_B:Number = 1; private static const IMAGE_SCALE:Number = 1; /** * Trajectory that the camera follows over time. Each element is an object * containing properties used to generate parameter values for flyTo(..). * fraction = 0 corresponds to the start of the trip; fraction = 1 * correspondsto the end of the trip. */ private var FLY_TRAJECTORY:Array = [ { fraction: 0, zoom: 6, attitude: new Attitude(0, 0, 0) }, { fraction: 0.2, zoom: 8.5, attitude: new Attitude(30, 30, 0) }, { fraction: 0.5, zoom: 9, attitude: new Attitude(30, 40, 0) }, { fraction: 1, zoom: 8, attitude: new Attitude(50, 50, 0) }, { fraction: 1.1, zoom: 8, attitude: new Attitude(130, 50, 0) }, { fraction: 1.2, zoom: 8, attitude: new Attitude(220, 50, 0) }, ]; /** * Number of panaramio photos for which we load data. We&apos;ll select a * subset of these approximately evenly spaced along the route. */ private static const NUM_GEOTAGGED_PHOTOS:int = 50; /** * Number of panaramio photos that we actually show. */ private static const NUM_SHOWN_PHOTOS:int = 7; /** * Scaling between real trip time and animation time. */ private static const SCALE_TIME:Number = 0.001; /** * getTimer() value at the instant that we start the trip. If this is 0 then * we have not yet started the car moving. */ private var startTimer:int = 0; /** * The current route. */ private var route:Route; /** * The polyline for the route. */ private var polyline:IPolyline; /** * The car marker. */ private var marker:Marker; /** * The cumulative duration in seconds over each step in the route. * cumulativeStepDuration[0] is 0; cumulativeStepDuration[1] adds the * duration of step 0; cumulativeStepDuration[2] adds the duration * of step 1; etc. */ private var cumulativeStepDuration:/*Number*/Array = []; /** * The cumulative distance in metres over each vertex in the route polyline. * cumulativeVertexDistance[0] is 0; cumulativeVertexDistance[1] adds the * distance to vertex 1; cumulativeVertexDistance[2] adds the distance to * vertex 2; etc. */ private var cumulativeVertexDistance:Array; /** * Array of photos loaded from Panoramio. This array has the same format as * the &apos;photos&apos; property within the JSON returned by the Panoramio API * (see http://www.panoramio.com/api/), with additional properties added to * individual photo elements to hold the loader structures that fetch * the actual images. */ private var photos:Array = []; /** * Array of polyline vertices, where each element is in world coordinates. * Several computations can be faster if we can use world coordinates * instead of LatLng coordinates. */ private var worldPoly:/*Point*/Array; /** * Whether the start button has been pressed. */ private var startButtonPressed:Boolean = false; /** * Saved event from onDirectionsSuccess call. */ private var directionsSuccessEvent:DirectionsEvent = null; /** * Start button. */ private var startButton:Sprite; /** * Alpha value used for the Panoramio image markers. */ private var markerAlpha:Number = 0; /** * Index of the current driving direction step. Used to update the * info window content each time we progress to a new step. */ private var currentStepIndex:int = -1; /** * The fly directions map constructor. * * @constructor */ public function FlyingDirections() { key="ABQIAAAA7QUChpcnvnmXxsjC7s1fCxQGj0PqsCtxKvarsoS-iqLdqZSKfxTd7Xf-2rEc_PC9o8IsJde80Wnj4g"; super(); addEventListener(MapEvent.MAP_PREINITIALIZE, onMapPreinitialize); addEventListener(MapEvent.MAP_READY, onMapReady); } /** * Handles map preintialize. Initializes the map center and zoom level. * * @param event The map event. */ private function onMapPreinitialize(event:MapEvent):void { setInitOptions(new MapOptions({ center: new LatLng(-26.1, 135.1), zoom: 4, viewMode: View.VIEWMODE_PERSPECTIVE, mapType:MapType.PHYSICAL_MAP_TYPE })); } /** * Handles map ready and looks up directions. * * @param event The map event. */ private function onMapReady(event:MapEvent):void { enableScrollWheelZoom(); enableContinuousZoom(); addControl(new NavigationControl()); // The driving animation will be updated on every frame. addEventListener(Event.ENTER_FRAME, enterFrame); addStartButton(); // We start the directions loading now, so that we&apos;re ready to go when // the user hits the start button. var directions:Directions = new Directions(); directions.addEventListener( DirectionsEvent.DIRECTIONS_SUCCESS, onDirectionsSuccess); directions.addEventListener( DirectionsEvent.DIRECTIONS_FAILURE, onDirectionsFailure); directions.load("48 Pirrama Rd, Pyrmont, NSW to Byron Bay, NSW"); } /** * Adds a big blue start button. */ private function addStartButton():void { startButton = new Sprite(); startButton.buttonMode = true; startButton.addEventListener(MouseEvent.CLICK, onStartClick); startButton.graphics.beginFill(0x1871ce); startButton.graphics.drawRoundRect(0, 0, 150, 100, 10, 10); startButton.graphics.endFill(); var startField:TextField = new TextField(); startField.autoSize = TextFieldAutoSize.LEFT; startField.defaultTextFormat = new TextFormat("_sans", 20, 0xffffff, true); startField.text = "Start!"; startButton.addChild(startField); startField.x = 0.5 * (startButton.width - startField.width); startField.y = 0.5 * (startButton.height - startField.height); startButton.filters = [ new DropShadowFilter() ]; var container:DisplayObjectContainer = getDisplayObject() as DisplayObjectContainer; container.addChild(startButton); startButton.x = 0.5 * (container.width - startButton.width); startButton.y = 0.5 * (container.height - startButton.height); var panoField:TextField = new TextField(); panoField.autoSize = TextFieldAutoSize.LEFT; panoField.defaultTextFormat = new TextFormat("_sans", 11, 0x000000, true); panoField.text = "Photos provided by Panoramio are under the copyright of their owners."; container.addChild(panoField); panoField.x = container.width - panoField.width - 5; panoField.y = 5; } /** * Handles directions success. Starts flying the route if everything * is ready. * * @param event The directions event. */ private function onDirectionsSuccess(event:DirectionsEvent):void { directionsSuccessEvent = event; flyRouteIfReady(); } /** * Handles click on the start button. Starts flying the route if everything * is ready. */ private function onStartClick(event:MouseEvent):void { startButton.removeEventListener(MouseEvent.CLICK, onStartClick); var container:DisplayObjectContainer = getDisplayObject() as DisplayObjectContainer; container.removeChild(startButton); startButtonPressed = true; flyRouteIfReady(); } /** * If we have loaded the directions and the start button has been pressed * start flying the directions route. */ private function flyRouteIfReady():void { if (!directionsSuccessEvent || !startButtonPressed) { return; } var directions:Directions = directionsSuccessEvent.directions; // Extract the route. route = directions.getRoute(0); // Draws the polyline showing the route. polyline = directions.createPolyline(); addOverlay(directions.createPolyline()); // Creates a car marker that is moved along the route. var car:DisplayObject = new Car(); marker = new Marker(route.startGeocode.point, new MarkerOptions({ icon: car, iconOffset: new Point(-car.width / 2, -car.height) })); addOverlay(marker); transformPolyToWorld(); createCumulativeArrays(); // Load Panoramio data for the region covered by the route. loadPanoramioData(directions.bounds); var duration:Number = route.duration; // Start a timer that will trigger the car moving after the lead in time. var leadInTimer:Timer = new Timer(LEAD_IN_DURATION * 1000, 1); leadInTimer.addEventListener(TimerEvent.TIMER, onLeadInDone); leadInTimer.start(); var flyTime:Number = -LEAD_IN_DURATION; // Set up the camera flight trajectory. for each (var flyStep:Object in FLY_TRAJECTORY) { var time:Number = flyStep.fraction * duration; var center:LatLng = latLngAt(time); var scaledTime:Number = time * SCALE_TIME; var zoom:Number = flyStep.zoom; var attitude:Attitude = flyStep.attitude; var elapsed:Number = scaledTime - flyTime; flyTime = scaledTime; flyTo(center, zoom, attitude, elapsed); } } /** * Loads Panoramio data for the route bounds. We load data about more photos * than we need, then select a subset lying along the route. * @param bounds Bounds within which to fetch images. */ private function loadPanoramioData(bounds:LatLngBounds):void { var params:Object = { order: "popularity", set: "full", from: "0", to: NUM_GEOTAGGED_PHOTOS.toString(10), size: "small", minx: bounds.getWest(), miny: bounds.getSouth(), maxx: bounds.getEast(), maxy: bounds.getNorth() }; var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest( "http://www.panoramio.com/map/get_panoramas.php?" + paramsToString(params)); loader.addEventListener(Event.COMPLETE, onPanoramioDataLoaded); loader.addEventListener(IOErrorEvent.IO_ERROR, onPanoramioDataFailed); loader.load(request); } /** * Transforms the route polyline to world coordinates. */ private function transformPolyToWorld():void { var numVertices:int = polyline.getVertexCount(); worldPoly = new Array(numVertices); for (var i:int = 0; i < numVertices; ++i) { var vertex:LatLng = polyline.getVertex(i); worldPoly[i] = fromLatLngToPoint(vertex, 0); } } /** * Returns the time at which the route approaches closest to the * given point. * @param world Point in world coordinates. * @return Route time at which the closest approach occurs. */ private function getTimeOfClosestApproach(world:Point):Number { var minDistSqr:Number = Number.MAX_VALUE; var numVertices:int = worldPoly.length; var x:Number = world.x; var y:Number = world.y; var minVertex:int = 0; for (var i:int = 0; i < numVertices; ++i) { var dx:Number = worldPoly[i].x - x; var dy:Number = worldPoly[i].y - y; var distSqr:Number = dx * dx + dy * dy; if (distSqr < minDistSqr) { minDistSqr = distSqr; minVertex = i; } } return cumulativeVertexDistance[minVertex]; } /** * Returns the array index of the first element that compares greater than * the given value. * @param ordered Ordered array of elements. * @param value Value to use for comparison. * @return Array index of the first element that compares greater than * the given value. */ private function upperBound(ordered:Array, value:Number, first:int=0, last:int=-1):int { if (last < 0) { last = ordered.length; } var count:int = last - first; var index:int; while (count > 0) { var step:int = count >> 1; index = first + step; if (value >= ordered[index]) { first = index + 1; count -= step - 1; } else { count = step; } } return first; } /** * Selects up to a given number of photos approximately evenly spaced along * the route. * @param ordered Array of photos, each of which is an object with * a property &apos;closestTime&apos;. * @param number Number of photos to select. */ private function selectEvenlySpacedPhotos(ordered:Array, number:int):Array { var start:Number = cumulativeVertexDistance[0]; var end:Number = cumulativeVertexDistance[cumulativeVertexDistance.length - 2]; var closestTimes:Array = []; for each (var photo:Object in ordered) { closestTimes.push(photo.closestTime); } var selectedPhotos:Array = []; for (var i:int = 0; i < number; ++i) { var idealTime:Number = start + ((end - start) * (i + 0.5) / number); var index:int = upperBound(closestTimes, idealTime); if (index < 1) { index = 0; } else if (index >= ordered.length) { index = ordered.length - 1; } else { var errorToPrev:Number = Math.abs(idealTime - closestTimes[index - 1]); var errorToNext:Number = Math.abs(idealTime - closestTimes[index]); if (errorToPrev < errorToNext) { --index; } } selectedPhotos.push(ordered[index]); } return selectedPhotos; } /** * Handles completion of loading the Panoramio index data. Selects from the * returned photo indices a subset of those that lie along the route and * initiates load of each of these. * @param event Load completion event. */ private function onPanoramioDataLoaded(event:Event):void { var loader:URLLoader = event.target as URLLoader; var decoder:JSONDecoder = new JSONDecoder(loader.data as String); var allPhotos:Array = decoder.getValue().photos; for each (var photo:Object in allPhotos) { var latLng:LatLng = new LatLng(photo.latitude, photo.longitude); photo.closestTime = getTimeOfClosestApproach(fromLatLngToPoint(latLng, 0)); } allPhotos.sortOn("closestTime", Array.NUMERIC); photos = selectEvenlySpacedPhotos(allPhotos, NUM_SHOWN_PHOTOS); for each (photo in photos) { var photoLoader:Loader = new Loader(); // The images aren&apos;t on panoramio.com: we can&apos;t acquire pixel access // using "new LoaderContext(true)". photoLoader.load( new URLRequest(photo.photo_file_url)); photo.loader = photoLoader; // Save the loader info: we use this to find the original element when // the load completes. photo.loaderInfo = photoLoader.contentLoaderInfo; photoLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, onPhotoLoaded); } } /** * Creates a MouseEvent listener function that will navigate to the given * URL in a new window. * @param url URL to which to navigate. */ private function createOnClickUrlOpener(url:String):Function { return function(event:MouseEvent):void { navigateToURL(new URLRequest(url)); }; } /** * Handles completion of loading an individual Panoramio image. * Adds a custom marker that displays the image. Initially this is made * invisible so that it can be faded in as needed. * @param event Load completion event. */ private function onPhotoLoaded(event:Event):void { var loaderInfo:LoaderInfo = event.target as LoaderInfo; // We need to find which photo element this image corresponds to. for each (var photo:Object in photos) { if (loaderInfo == photo.loaderInfo) { var imageMarker:Sprite = createImageMarker(photo.loader, photo.owner_name, photo.owner_url); var options:MarkerOptions = new MarkerOptions({ icon: imageMarker, hasShadow: true, iconAlignment: MarkerOptions.ALIGN_BOTTOM | MarkerOptions.ALIGN_LEFT }); var latLng:LatLng = new LatLng(photo.latitude, photo.longitude); var marker:Marker = new Marker(latLng, options); photo.marker = marker; addOverlay(marker); // A hack: we add the actual image after the overlay has been added, // which creates the shadow, so that the shadow is valid even if we // don&apos;t have security privileges to generate the shadow from the // image. marker.foreground.visible = false; marker.shadow.alpha = 0; var imageHolder:Sprite = new Sprite(); imageHolder.addChild(photo.loader); imageHolder.buttonMode = true; imageHolder.addEventListener( MouseEvent.CLICK, createOnClickUrlOpener(photo.photo_url)); imageMarker.addChild(imageHolder); return; } } trace("An image was loaded which could not be found in the photo array."); } /** * Creates a custom marker showing an image. */ private function createImageMarker(child:DisplayObject, ownerName:String, ownerUrl:String):Sprite { var content:Sprite = new Sprite(); var panoramioIcon:Bitmap = new PanoramioIcon(); var iconHolder:Sprite = new Sprite(); iconHolder.addChild(panoramioIcon); iconHolder.buttonMode = true; iconHolder.addEventListener(MouseEvent.CLICK, onPanoramioIconClick); panoramioIcon.x = BORDER_L; panoramioIcon.y = BORDER_T; content.addChild(iconHolder); // NOTE: we add the image as a child only after we&apos;ve added the marker // to the map. Currently the API requires this if it&apos;s to generate the // shadow for unprivileged content. // Shrink the image, so that it doesn&apos;t obcure too much screen space. // Ideally, we&apos;d subsample, but we don&apos;t have pixel level access. child.scaleX = IMAGE_SCALE; child.scaleY = IMAGE_SCALE; var imageW:Number = child.width; var imageH:Number = child.height; child.x = BORDER_L + 30; child.y = BORDER_T + iconHolder.height + GAP_T; var authorField:TextField = new TextField(); authorField.autoSize = TextFieldAutoSize.LEFT; authorField.defaultTextFormat = new TextFormat("_sans", 12); authorField.text = "author:"; content.addChild(authorField); authorField.x = BORDER_L; authorField.y = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B; var ownerField:TextField = new TextField(); ownerField.autoSize = TextFieldAutoSize.LEFT; var textFormat:TextFormat = new TextFormat("_sans", 14, 0x0e5f9a); ownerField.defaultTextFormat = textFormat; ownerField.htmlText = "<a href=\"" + ownerUrl + "\" target=\"_blank\">" + ownerName + "</a>"; content.addChild(ownerField); ownerField.x = BORDER_L + authorField.width; ownerField.y = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B; var totalW:Number = BORDER_L + Math.max(imageW, ownerField.width + authorField.width) + BORDER_R; var totalH:Number = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B + ownerField.height + BORDER_B; content.graphics.beginFill(0xffffff); content.graphics.drawRoundRect(0, 0, totalW, totalH, 10, 10); content.graphics.endFill(); var marker:Sprite = new Sprite(); marker.addChild(content); content.x = 30; content.y = 0; marker.graphics.lineStyle(); marker.graphics.beginFill(0xff0000); marker.graphics.drawCircle(0, totalH + 30, 3); marker.graphics.endFill(); marker.graphics.lineStyle(2, 0xffffff); marker.graphics.moveTo(30 + 10, totalH - 10); marker.graphics.lineTo(0, totalH + 30); return marker; } /** * Handles click on the Panoramio icon. */ private function onPanoramioIconClick(event:MouseEvent):void { navigateToURL(new URLRequest(PANORAMIO_HOME)); } /** * Handles failure of a Panoramio image load. */ private function onPanoramioDataFailed(event:IOErrorEvent):void { trace("Load of image failed: " + event); } /** * Returns a string containing cgi query parameters. * @param Associative array mapping query parameter key to value. * @return String containing cgi query parameters. */ private static function paramsToString(params:Object):String { var result:String = ""; var separator:String = ""; for (var key:String in params) { result += separator + encodeURIComponent(key) + "=" + encodeURIComponent(params[key]); separator = "&"; } return result; } /** * Called once the lead-in flight is done. Starts the car driving along * the route and starts a timer to begin fade in of the Panoramio * images in 1.5 seconds. */ private function onLeadInDone(event:Event):void { // Set startTimer non-zero so that the car starts to move. startTimer = getTimer(); // Start a timer that will fade in the Panoramio images. var fadeInTimer:Timer = new Timer(1500, 1); fadeInTimer.addEventListener(TimerEvent.TIMER, onFadeInTimer); fadeInTimer.start(); } /** * Handles the fade in timer&apos;s TIMER event. Sets markerAlpha above zero * which causes the frame enter handler to fade in the markers. */ private function onFadeInTimer(event:Event):void { markerAlpha = 0.01; } /** * The end time of the flight. */ private function get endTime():Number { if (!cumulativeStepDuration || cumulativeStepDuration.length == 0) { return startTimer; } return startTimer + cumulativeStepDuration[cumulativeStepDuration.length - 1]; } /** * Creates the cumulative arrays, cumulativeStepDuration and * cumulativeVertexDistance. */ private function createCumulativeArrays():void { cumulativeStepDuration = new Array(route.numSteps + 1); cumulativeVertexDistance = new Array(polyline.getVertexCount() + 1); var polylineTotal:Number = 0; var total:Number = 0; var numVertices:int = polyline.getVertexCount(); for (var stepIndex:int = 0; stepIndex < route.numSteps; ++stepIndex) { cumulativeStepDuration[stepIndex] = total; total += route.getStep(stepIndex).duration; var startVertex:int = stepIndex >= 0 ? route.getStep(stepIndex).polylineIndex : 0; var endVertex:int = stepIndex < (route.numSteps - 1) ? route.getStep(stepIndex + 1).polylineIndex : numVertices; var duration:Number = route.getStep(stepIndex).duration; var stepVertices:int = endVertex - startVertex; var latLng:LatLng = polyline.getVertex(startVertex); for (var vertex:int = startVertex; vertex < endVertex; ++vertex) { cumulativeVertexDistance[vertex] = polylineTotal; if (vertex < numVertices - 1) { var nextLatLng:LatLng = polyline.getVertex(vertex + 1); polylineTotal += nextLatLng.distanceFrom(latLng); } latLng = nextLatLng; } } cumulativeStepDuration[stepIndex] = total; } /** * Opens the info window above the car icon that details the given * step of the driving directions. * @param stepIndex Index of the current step. */ private function openInfoForStep(stepIndex:int):void { // Sets the content of the info window. var content:String; if (stepIndex >= route.numSteps) { content = "<b>" + route.endGeocode.address + "</b>" + "<br /><br />" + route.summaryHtml; } else { content = "<b>" + stepIndex + ".</b> " + route.getStep(stepIndex).descriptionHtml; } marker.openInfoWindow(new InfoWindowOptions({ contentHTML: content })); } /** * Displays the driving directions step appropriate for the given time. * Opens the info window showing the step instructions each time we * progress to a new step. * @param time Time for which to display the step. */ private function displayStepAt(time:Number):void { var stepIndex:int = upperBound(cumulativeStepDuration, time) - 1; var minStepIndex:int = 0; var maxStepIndex:int = route.numSteps - 1; if (stepIndex >= 0 && stepIndex <= maxStepIndex && currentStepIndex != stepIndex) { openInfoForStep(stepIndex); currentStepIndex = stepIndex; } } /** * Returns the LatLng at which the car should be positioned at the given * time. * @param time Time for which LatLng should be found. * @return LatLng. */ private function latLngAt(time:Number):LatLng { var stepIndex:int = upperBound(cumulativeStepDuration, time) - 1; var minStepIndex:int = 0; var maxStepIndex:int = route.numSteps - 1; if (stepIndex < minStepIndex) { return route.startGeocode.point; } else if (stepIndex > maxStepIndex) { return route.endGeocode.point; } var stepStart:Number = cumulativeStepDuration[stepIndex]; var stepEnd:Number = cumulativeStepDuration[stepIndex + 1]; var stepFraction:Number = (time - stepStart) / (stepEnd - stepStart); var startVertex:int = route.getStep(stepIndex).polylineIndex; var endVertex:int = (stepIndex + 1) < route.numSteps ? route.getStep(stepIndex + 1).polylineIndex : polyline.getVertexCount(); var stepVertices:int = endVertex - startVertex; var stepLeng

    Read the article

< Previous Page | 1 2