Search Results

Search found 547 results on 22 pages for 'marker'.

Page 3/22 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Google Maps, Ruby on Rails, Zoom level with one marker

    - by Enric Ribas
    I am adding google maps support with apneadiving / Google-Maps-for-Rails (thanks awesome gem) I am finding one slight glitch, however, which very likely is my fault. auto_zoom works great when there are multiple markers. However, when there is only one marker it is zoomed in to the max level which is not pretty. "zoom" will only work when auto_zoom is false, so that's not what I want. So therefore you could use "maxZoom" but now users cannot zoom in manually beyond that point which is not what I want. Is there a way around this? Is my explanation making sense? Is this a limitation of Google Maps API? Thanks...

    Read the article

  • Externalising Google Maps InfoWindow Content When Marker Is Selected

    - by Mark
    Hi, I'm wondering if anyone knows whether it is possible to take the content of a Google Maps InfoWindow and place it in an external DIV when the marker on the map is clicked? I've had a good dig around both the API docs and Google to see if I can find any examples or information relating to this but have had no luck so far. However I've not had a lot of time since I got asked about this one so I have had to skim a bit so it could be that I've missed something but nothing seems to be jumping out at me. Essentially I'd just like to know if this is indeed possible so that I don't waste anymore time researching something that is currently not possible with Google Maps. However if anyone has any code, examples, or ideas about how to go about doing this then that would be a very much appreciated! Thanks, Mark

    Read the article

  • convert xml.documentElement.getElementsByTagName("marker")[index].getAttribute(temp) to string in ja

    - by user324884
    I am parsing xml file in javascript and after that want to cancatenate all the the data into string. but failing to do the same and it is returning undefined. GDownloadUrl("./include/dataemp2.xml", function(data) { var xml = GXml.parse(data); markers = xml.documentElement.getElementsByTagName("marker"); for(var t=0;t<18;t++) { var temp= markers[index].getAttribute("address"); html = html + temp; } }); it is returning as undefined because temp is not concatenating in "html"; whereas when i do this like html = html +markers[index].getAttribute("address"); it is giving me expected output;

    Read the article

  • Mapstraction: Changing an Icon's image URL after it has been added?

    - by Paul Owens
    I am trying to use marker.setIcon() to change a markers image. However it appears that although this changes the marker.iconUrl attribute the icon itself is using marker.proprietary_marker.$.icon.image to display the markers image - so the markers icon remains unchanged. Is there a way to dynamically change the marker.proprietary_marker.$.icon.image? Add a marker. Check the icon's image url and the proprietary icon's image - they're the same. Change the icon. Again check the Urls. Now the Icon Url has changed but the marker still shows the old image which is in the proprietary marker object. <head> <title>Map Test</title> <script src="http://maps.google.com/maps?file=api&v=2&key=Your-Google-API-Key" type="text/javascript"></script> <script src="mapstraction.js"></script> <script type="text/javascript"> var map; var marker; function getMap(){ map = new mxn.Mapstraction('myMap','google'); map.setCenterAndZoom(new mxn.LatLonPoint(45.559242,-122.636467), 15); } function addMarker(){ marker = new mxn.Marker(new mxn.LatLonPoint(45.559242, -122.636467)); marker.addData({infoBubble : "Text", label : "Label", marker : 4, icon: "http://mapscripting.com/examples/mashups/richter-high.png"}); map.addMarker(marker); } function changeIcon(){ marker.setIcon("http://assets1.mapufacture.com/images/markers/usgs_marker.png"); } function showIconURL(){ alert(marker.iconUrl); } function showProprietaryIconURL(){ alert(marker.proprietary_marker.$.icon.image); } </script> </head> <body onload="getMap()"> <div id="myMap" style="width:627px; height:412px;"></div> <div> <input type="button" value="add marker" OnClick="addMarker();"> <input type="button" value="change icon" OnClick="changeIcon();"> <input type="button" value="show icon URL" OnClick="showIconURL();"> <input type="button" value="show proprierty icon URL " OnClick="showProprietaryIconURL();"> </div> </body> </html>

    Read the article

  • NotApplicable marker with display pattern

    - by Jeff Barger
    Ok, so I'm pretty new to Cocoa, especially Bindings, but here's what I'm trying to do. I've got a Core Data model consisting of two entities: Category and Item. Category has a to-many relationship to Item called children, and Item has a relationship to Category called parent. Item has two attributes that Category does not have: quantity and desiredQuantity. What I'd like to do is display the tree in an NSOutlineView with two columns. One column is bound to the name of either the Category or the Item. I want to the second column to display something along the lines of 2 of 5 for the Item rows and nothing at all for the Category rows. When I use a display pattern, the Category rows end up showing of I noticed that if I don't use a display pattern for the second column, and instead just bind its Value to either the quantity or the desiredQuantity, the Category rows show nothing; its only if I try to use the display pattern. How can I make it display nothing for the Category rows and still use the display pattern? Or can I? Edit: I guess I didn't explain what the NotApplicable marker has to do with anything - Category does have properties for quantity and desiredQuantity, but they just return NSNotApplicableMarker.

    Read the article

  • Adding marker to the retrieved location

    - by Rahul Varma
    I have displayed the map in my app by using the following code. I have retrieved info from the database and displayed the map. Now i want to add marker to the retrieved location... googleMao.java public class googleMap extends MapActivity{ private MapView mapView; private MapController mc; GeoPoint p; long s; Cursor cur; SQLiteDatabase db; createSqliteHelper csh; String qurry; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map); // String qurry=getIntent().getStringExtra("value"); //here is calling the map string qurry s = getIntent().getLongExtra("value",2); map(); mapView = (MapView) findViewById(R.id.mapview1); LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom); View zoomView = mapView.getZoomControls(); zoomLayout.addView(zoomView, new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); //mapView.displayZoomControls(true); mapView.setBuiltInZoomControls(true); mc = mapView.getController(); String coordinates[] = {"1.352566007", "103.78921587"}; double lat = Double.parseDouble(coordinates[0]); double lng = Double.parseDouble(coordinates[1]); Geocoder geoCoder = new Geocoder(this, Locale.getDefault()); try { List<Address> addresses = geoCoder.getFromLocationName(qurry,5); String add = ""; if (addresses.size() > 0) { p = new GeoPoint( (int) (addresses.get(0).getLatitude() * 1E6), (int) (addresses.get(0).getLongitude() * 1E6)); mc.animateTo(p); mapView.invalidate(); mc.setZoom(6); } } catch (IOException e) { e.printStackTrace(); } } @Override protected boolean isRouteDisplayed() { // Required by MapActivity return false; } public void map() { String[] str={"type"}; int[] i={R.id.type}; csh=new createSqliteHelper(this); db=csh.getReadableDatabase(); cur=db.rawQuery("select type from restaurants where _id="+s,null); if(cur.moveToFirst()) { qurry=cur.getString(cur.getColumnIndex("type")); } } }

    Read the article

  • How to change the colors of a legend item in flex legend?

    - by AngelHeart
    in my flex chart I changed the fill of the PieSeries to use custom colors (set colors that I was prepared to be used according to values in the data provider of the Pie Chart)... The problem that the legend that is linked to my PieChart still shows the flex default colors and not the new colors from the PieChart series! Any idea how can I render the marker fill color of the flex legend items to meet the colors in the Pie Chart?

    Read the article

  • Separating arguments to a function, in locales with comma as decimal marker

    - by Chris Pousset
    In locales, e.g. French, with comma as decimal indicator (where "5,2" means five and two-tenths), how do users separate function arguments from each other? For example, in many programming/scripting languages, I could specify MAX(1.5, X) in a EN-US locale. How do you avoid the ambiguity between the comma as decimal indicator, and as argument separator? In particular, I'm interested in how software that's perceived as user-friendly in the foreign locale does it. Obviously, it's a no-brainer to say, "thou shalt use decimal POINTs", but that's not particularly "friendly".

    Read the article

  • Add LINQ Auto-Generated Value Marker [Column(IsDbGenerated=true)] in Buddy Class

    - by Alex
    Hello, is it possible to decorate a field of a LINQ generated class with [Column(IsDbGenerated=true)] using a buddy class (which is linked to the LINQ class via [MetadataType(typeof(BuddyMetadata))]) ? My goal is to be able to clear and repopulate the LINQ ORM designer without having to set the "Auto Generate Value" property manually every time to re-establish the fact that certain columns are autogenerated. Thanks!

    Read the article

  • Cut a file based on a text marker

    - by Mustafa
    I have a text file that has the following layout: text text .. CUT HERE text text .. The literal CUT HERE appears only once. What I want to do using shell scripting, is to produce another file containing all the text below CUT HERE, i.e. ignore whatever above CUT HERE. Thanks.

    Read the article

  • Google Maps API : V2 : marker icons are not square

    - by PlanetUnknown
    I have generated a bunch of png files to use as markers on my site. However when I applied them using GIcon(). I see that they are squeezed such that the height is more than the width. This even though my png files are exactly 22x22 pixels. I don't think I have the resources to generate the whole set to fit the odd 20x34 or some such size. Is there any way this can be fixed ? I tried specifying a GSize() to unsqueeze them, but that didn't work.

    Read the article

  • Javascript indexOf() always returns -1

    - by Thomas
    I try to retrieve the index of en element in an array. This works perfectly var onCreate = function (event) { console.assert(markers[markerId] === undefined); var markerId = event.markerId; markers[markerId] = {}; var marker = markers[markerId]; // create the container object marker.object3d = new THREE.Object3D(); marker.object3d.matrixAutoUpdate = false; scene.add(marker.object3d); //UPDATE ARRAY HOLDING CURRENT MARKERS console.log("ON CREATE"); console.log("current detected markers: " + currentMarkers); var idx = currentMarkers.indexOf(markerId); // Find the index console.log("marker " + event.markerId + " has index: " + idx); if(idx==-1) // if does not exist currentMarkers.push(markerId); But this doesnt... var onDelete = function (event) { console.assert(markers[event.markerId] !== undefined); var markerId = event.markerId; //UPDATE ARRAY HOLDING CURRENT MARKERS console.log("ON DELETE"); console.log("current detected markers: " + currentMarkers); var idxx = currentMarkers.indexOf(markerId); // Find the index console.log("marker " + markerId + " has index: " + idxx); if(idxx != -1) {// if DOES exist currentMarkers.splice(idxx, 1); //Delete var idxxx = currentMarkersCoverChecked.indexOf(markerId); // Find the index if(idxxx == -1) // if does NOT exist, so if not being checked checkMarkerCovered(markerId); } onDeleteRandom(markerId); var marker = markers[markerId]; scene.remove(marker.object3d); delete markers[markerId]; Look at my console output: ON CREATE current detected markers: 2,1,4 marker 3 has index: -1 ON CREATE main.js:266 current detected markers: 2,1,4,3 marker 4 has index: 2 ON DELETE current detected markers: 2,1,4,3 marker 2 has index: -1 ON CREATE current detected markers: 2,1,4,3 marker 2 has index: 0 ON DELETE current detected markers: 2,1,4,3 marker 1 has index: -1

    Read the article

  • Generate custom marker (icon) out of two images in Leaflet

    - by Rmatt
    In Javascript/CoffeeScript, using Leaflet to display a map, I would like to have custom markers out of a two custom images, and also featuring a shadow for the pin : I want to have a "background" image with a color (or shape) to identify the category On top, I want to have inside this image a specific image (logo) for each pin I didn't find out how I could do that... Setting one image is quite easy but I don't know how to overlay them. I could also consider using a tool to superpose/group/overlay these images (locally ?) before in order to send only one to the Icon Leaflet Class, but also there, I wouldn't know which tool to use. Nevertheless, I still think that a double overlay would be more efficient and that my case could be useful for several people.

    Read the article

  • How to limit click'n'drag movement to an area?

    - by Vexille
    I apologize for the somewhat generic title. I'm really don't have much clue about how to accomplish what I'm trying to do, which is making it harder even to research a possible solution. I'm trying to implement a path marker of sorts (maybe there's a most suitable name for it, but this is the best I could come up with). In front of the player there will be a path marker, which will determine how the player will move once he finishes planning his turn. The player may click and drag the marker to the position they choose, but the marker can only be moved within a defined working area (the gray bit). So I'm now stuck with two problems: First of all, how exactly should I define that workable area? I can imagine maybe two vectors that have the player as a starting point to form the workable angle, and maybe those two arcs could come from circles that have their center where the player is, but I definetly don't know how to put this all together. And secondly, after I've defined the area where the marker can be placed, how can I enforce that the marker should only stay within that area? For example, if the player clicks and drags the marker around, it may move freely within the working area, but must not leave the boundaries of the area. So for example, if the player starts dragging the marker upwards, it will move upwards until it hits he end of the working area (first diagram below), but if after that the player starts dragging sideways, the marker must follow the drag while still within the area (second diagram below). I hope this wasn't all too confusing. Thanks, guys.

    Read the article

  • How to access Google Maps API v3 marker's DIV and it's pixel position?

    - by Ray Yun
    Instead of google maps api's default info window, I'm going to use other jquery tooltip plugin over marker. So I need to get marker's DIV and its pixel position. But couldn't get it because there are no id or class for certain marker. Only I can access map canvas div from marker object and undocumented pixelBounds object. How can I access marker's DIV? Where can I get DIV's pixel position? Can I convert lat-lng position to pixel values?

    Read the article

  • Passing XML markers to Google Map

    - by djmadscribbler
    I've been creating a V3 Google map based on this example from Mike Williams http://www.geocodezip.com/v3_MW_example_map3.html I've run into a bit of a problem though. If I have no parameters in my URL then I get the error "id is undefined idmarkers [id.toLowerCase()] = marker;" in Firebug and only one marker will show up. If I have a parameter (?id=105 for example) then all the sidebar links say 105 (or whatever the parameter in the URL was) instead of their respective label as listed in the XML file and a random infowindow will be opened instead of the window for the id in the URL. Here is my javascript: var map = null; var lastmarker = null; // ========== Read paramaters that have been passed in ========== // Before we go looking for the passed parameters, set some defaults // in case there are no parameters var id; var index = -1; // these set the initial center, zoom and maptype for the map // if it is not specified in the query string var lat = 42.194741; var lng = -121.700301; var zoom = 18; var maptype = google.maps.MapTypeId.HYBRID; function MapTypeId2UrlValue(maptype) { var urlValue = 'm'; switch (maptype) { case google.maps.MapTypeId.HYBRID: urlValue = 'h'; break; case google.maps.MapTypeId.SATELLITE: urlValue = 'k'; break; case google.maps.MapTypeId.TERRAIN: urlValue = 't'; break; default: case google.maps.MapTypeId.ROADMAP: urlValue = 'm'; break; } return urlValue; } // If there are any parameters at eh end of the URL, they will be in location.search // looking something like "?marker=3" // skip the first character, we are not interested in the "?" var query = location.search.substring(1); // split the rest at each "&" character to give a list of "argname=value" pairs var pairs = query.split("&"); for (var i = 0; i < pairs.length; i++) { // break each pair at the first "=" to obtain the argname and value var pos = pairs[i].indexOf("="); var argname = pairs[i].substring(0, pos).toLowerCase(); var value = pairs[i].substring(pos + 1).toLowerCase(); // process each possible argname - use unescape() if theres any chance of spaces if (argname == "id") { id = unescape(value); } if (argname == "marker") { index = parseFloat(value); } if (argname == "lat") { lat = parseFloat(value); } if (argname == "lng") { lng = parseFloat(value); } if (argname == "zoom") { zoom = parseInt(value); } if (argname == "type") { // from the v3 documentation 8/24/2010 // HYBRID This map type displays a transparent layer of major streets on satellite images. // ROADMAP This map type displays a normal street map. // SATELLITE This map type displays satellite images. // TERRAIN This map type displays maps with physical features such as terrain and vegetation. if (value == "m") { maptype = google.maps.MapTypeId.ROADMAP; } if (value == "k") { maptype = google.maps.MapTypeId.SATELLITE; } if (value == "h") { maptype = google.maps.MapTypeId.HYBRID; } if (value == "t") { maptype = google.maps.MapTypeId.TERRAIN; } } } // this variable will collect the html which will eventually be placed in the side_bar var side_bar_html = ""; // arrays to hold copies of the markers and html used by the side_bar // because the function closure trick doesnt work there var gmarkers = []; var idmarkers = []; // global "map" variable var map = null; // A function to create the marker and set up the event window function function createMarker(point, icon, label, html) { var contentString = html; var marker = new google.maps.Marker({ position: point, map: map, title: label, icon: icon, zIndex: Math.round(point.lat() * -100000) << 5 }); marker.id = id; marker.index = gmarkers.length; google.maps.event.addListener(marker, 'click', function () { lastmarker = new Object; lastmarker.id = marker.id; lastmarker.index = marker.index; infowindow.setContent(contentString); infowindow.open(map, marker); }); // save the info we need to use later for the side_bar gmarkers.push(marker); idmarkers[id.toLowerCase()] = marker; // add a line to the side_bar html side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length - 1) + ')">' + id + '<\/a><br>'; } // This function picks up the click and opens the corresponding info window function myclick(i) { google.maps.event.trigger(gmarkers[i], "click"); } function makeLink() { var mapinfo = "lat=" + map.getCenter().lat().toFixed(6) + "&lng=" + map.getCenter().lng().toFixed(6) + "&zoom=" + map.getZoom() + "&type=" + MapTypeId2UrlValue(map.getMapTypeId()); if (lastmarker) { var a = "/about/map/default.aspx?id=" + lastmarker.id + "&" + mapinfo; var b = "/about/map/default.aspx?marker=" + lastmarker.index + "&" + mapinfo; } else { var a = "/about/map/default.aspx?" + mapinfo; var b = a; } document.getElementById("idlink").innerHTML = '<a href="' + a + '" id=url target=_new>- Link directly to this page by id</a> (id in xml file also entry &quot;name&quot; in sidebar menu)'; document.getElementById("indexlink").innerHTML = '<a href="' + b + '" id=url target=_new>- Link directly to this page by index</a> (position in gmarkers array)'; } function initialize() { // create the map var myOptions = { zoom: zoom, center: new google.maps.LatLng(lat, lng), mapTypeId: maptype, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }, navigationControl: true, mapTypeId: google.maps.MapTypeId.HYBRID }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var stylesarray = [ { featureType: "poi", elementType: "labels", stylers: [ { visibility: "off" } ] }, { featureType: "landscape.man_made", elementType: "labels", stylers: [ { visibility: "off" } ] } ]; var options = map.setOptions({ styles: stylesarray }); // Make the link the first time when the page opens makeLink(); // Make the link again whenever the map changes google.maps.event.addListener(map, 'maptypeid_changed', makeLink); google.maps.event.addListener(map, 'center_changed', makeLink); google.maps.event.addListener(map, 'bounds_changed', makeLink); google.maps.event.addListener(map, 'zoom_changed', makeLink); google.maps.event.addListener(map, 'click', function () { lastmarker = null; makeLink(); infowindow.close(); }); // Read the data from example.xml downloadUrl("example.xml", function (doc) { var xmlDoc = xmlParse(doc); var markers = xmlDoc.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { // obtain the attribues of each marker var lat = parseFloat(markers[i].getAttribute("lat")); var lng = parseFloat(markers[i].getAttribute("lng")); var point = new google.maps.LatLng(lat, lng); var html = markers[i].getAttribute("html"); var label = markers[i].getAttribute("label"); var icon = markers[i].getAttribute("icon"); // create the marker var marker = createMarker(point, icon, label, html); } // put the assembled side_bar_html contents into the side_bar div document.getElementById("side_bar").innerHTML = side_bar_html; // ========= If a parameter was passed, open the info window ========== if (id) { if (idmarkers[id]) { google.maps.event.trigger(idmarkers[id], "click"); } else { alert("id " + id + " does not match any marker"); } } if (index > -1) { if (index < gmarkers.length) { google.maps.event.trigger(gmarkers[index], "click"); } else { alert("marker " + index + " does not exist"); } } }); } var infowindow = new google.maps.InfoWindow( { size: new google.maps.Size(150, 50) }); google.maps.event.addDomListener(window, "load", initialize); And here is an example of my XML formatting <marker lat="42.196175" lng="-121.699224" html="This is the information about 104" iconimage="/about/map/images/104.png" label="104" />

    Read the article

  • How do I store more information in a marker?

    - by Sebastian
    Hello, I'm using Google Maps v3 and I build in the server side a json collection of location data. So when I receive that, I iterate through that collection and create a marker object for each and every one of them. For each of these markers, I bind them with the click event, so when the user clicks on a marker in the map, it displays an infoWindow with data related to the associated location. I have an array to store all the location got from the server that holds the retrieved json objects and their corresponding marker. The problem is that, even when I have an array that I can reference or iterate through, I need to not only get the marker object when the user clicks on them, but also the location object, that stores more information. I tried to mantain this array of objects and reference it from the calling object without success, because the function is called by the marker and not the location object. So I thought if it's possible to store more information in the google maps marker object like using a general purpose field. Please let me know if more information is needed. Thanks!

    Read the article

  • Google Maps API V3: How to jump to a specific marker from outside the map?

    - by Tom
    I have a map with two markers on it. The initial view of the map only shows one marker, and I want to provide a link next to the map that will move the map to the 2nd marker when clicked. Here's a demo of what I want, using v2 of the API: http://arts.brighton.ac.uk/contact-university-of-brighton-faculty-of-arts (note the links below the map) Here's what I have so far: <script type="text/javascript"> function initialize() { var latlng = new google.maps.LatLng(50.823817, -0.135634); var myOptions = { zoom: 13, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU } , scaleControl: false }; var map = new google.maps.Map(document.getElementById("map"), myOptions); // 1st marker var marker1 = new google.maps.Marker({ position: new google.maps.LatLng(50.823817, -0.135634), map: map, title: 'my title' }); var infowindow = new google.maps.InfoWindow({ content: 'my window content' }); google.maps.event.addListener(marker1, 'click', function() { infowindow.open(map, marker1); }); // 2nd marker var marker2 = new google.maps.Marker({ position: new google.maps.LatLng(51.5262405, -0.074549), map: map, title: 'my 2nd title'}); var infowindow2 = new google.maps.InfoWindow({ content: 'content for my 2nd window' }); google.maps.event.addListener(marker2, 'click', function() { infowindow2.open(map, marker2); }); } </script> So what I'd like to add is a link to marker2, to move the map some 50-odd miles up, e.g. <a href="#marker2">Second location</a>. How would I do this?

    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

  • Google Maps: marker icons are multi over same location, why?

    - by JakiT
    I'm using Google Maps and have the map set to height/width=100%. I noticed that when I resize the browser window, my map marker icons appear to redraw on top of the same location. Meaning, if I should only have 1 map marker icon on "987 Main St", when I resize the browser window - multiple map marker icons are being now draw on top of "987 Main St" that shouldn't be there. Any ideas why this is happening and how to prevent it? UPDATE: Link to actual code

    Read the article

  • Google Maps: marker icons are multi-drawing over same location, why?

    - by JakiT
    I'm using Google Maps and have the map set to height/width=100%. I noticed that when I resize the browser window, my map marker icons appear to redraw on top of the same location. Meaning, if I should only have 1 map marker icon on "987 Main St", when I resize the browser window - multiple map marker icons are being now draw on top of "987 Main St" that shouldn't be there. Any ideas why this is happening and how to prevent it? UPDATE: Link to actual code

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >