写真をドラッグドロップで地図に配置
写真をドラッグドロップで地図に配置
ちょいと旅行に行ってきたのでせっかくなので写真をマップに簡単に張り付けられたらなぁってことで練習がてら作ってみました。
こんな感じ
http://moeten.info/flex/20081202_tripGoogleMap/bin-release/index.html
ソースはこちら
めさんこきたない。
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationCompleteHandler(event)" backgroundGradientColors="[0xffffff,0xcccccc]" viewSourceURL="srcview/index.html"> <mx:Script> <![CDATA[ import mx.controls.Image; import mx.core.DragSource; import mx.managers.DragManager; import mx.events.DragEvent; import com.google.maps.MapEvent; import com.google.maps.LatLng; import com.google.maps.Map; import com.google.maps.InfoWindowOptions; import com.google.maps.styles.*; import com.google.maps.interfaces.IPolyline; import com.google.maps.overlays.*; import com.google.maps.controls.*; import com.google.maps.*; import com.google.maps.services.*; [Bindable]public var myXMLDATA:XMLList; //マップ作製 private var map:Map; private function creationCompleteHandler(e:Event):void{ makeMap(); } private function makeMap():void{ var myContextMenu:ContextMenu = new ContextMenu(); var item:ContextMenuItem = new ContextMenuItem("このマーカーを削除"); myContextMenu.customItems.push(item); item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemSelectHandler2); myUI.contextMenu = myContextMenu; map = new Map(); map.key = "ABQIAAAAq9Z1Z3_S-AQpWPqQe5Gh1RQwYXHktz2QAm1LJMiOVVXt_FOHEhSgjc9KbBWBSWEOkPfrvuhvcDhCTQ"; myUI.addChild( map ); map.language = "JP"; map.width = myUI.width; map.height = myUI.height; map.addEventListener( MapEvent.MAP_READY, onMapReady ); } private function menuItemSelectHandler2(e:ContextMenuEvent):void{ if( e.currentTarget.caption == "このマーカーを削除"){ map.removeOverlay(markerArr[nowMarkerID]); markerArr[nowMarkerID] = null; htsFileUpdate.send({ "id":nowMarkerID, "clear":"on" }); } } private function onMapReady(e:Event):void{ //装飾追加 var zoomControl:ZoomControl = new ZoomControl() var z:ZoomControlOptions = new ZoomControlOptions(); map.addControl(zoomControl); var pos:PositionControl = new PositionControl(); map.addControl(pos); map.enableContinuousZoom(); map.setCenter( new LatLng(35.684072,139.769697) , 13, MapType.NORMAL_MAP_TYPE ); htsFileList.send(); } //画像ファイルを選択 import flash.net.FileReference; private var myFileReferenceList:FileReferenceList; private function fileSelect():void{ myFileReferenceList = new FileReferenceList(); myFileReferenceList.browse( new Array( new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png") )); myFileReferenceList.addEventListener(Event.SELECT , selectHandler ); } private var urlRequest:URLRequest; private function selectHandler(e:Event):void{ var urlVariables:URLVariables = new URLVariables(); urlVariables.imgMaxWidth = 100; urlVariables.imgMaxHeight = 200; urlRequest = new URLRequest(); urlRequest.url = "http://moeten.info/flex/20081202_tripGoogleMap/?mode=fileupload"; urlRequest.method = URLRequestMethod.POST; urlRequest.data = urlVariables; for (var i:int = 0; i < myFileReferenceList.fileList.length ; i++ ){ var fileReference:FileReference = new FileReference(); fileReference = FileReference( myFileReferenceList.fileList[i] ); fileReference.addEventListener( DataEvent.UPLOAD_COMPLETE_DATA, onUploadCompleteData ); fileReference.upload( urlRequest ); } } private function onUploadCompleteData(e:Event):void{ } //住所から緯度経度取得 private function getLatLngByZyuusyo():void{ var geo:ClientGeocoder = new ClientGeocoder( new ClientGeocoderOptions( {countryCode: "JP"} ) ); geo.geocode(zyuusyoTxt.text); geo.addEventListener(GeocodingEvent.GEOCODING_SUCCESS,onGeocodeSuccessHandler ); } private function onGeocodeSuccessHandler(e:GeocodingEvent):void{ var placemarks:Array = e.response.placemarks; map.setCenter(placemarks[0].point); } //郵便番号から緯度経度取得 private function getLatLngByZipcode():void{ htsZip.send({"zn":yuubin1Txt.text + yuubin2Txt.text}); } private function onHtsZipResultHandler(e:Event):void{ zyuusyoTxt.text = htsZip.lastResult.ADDRESS_value.value.@state + htsZip.lastResult.ADDRESS_value.value.@city + htsZip.lastResult.ADDRESS_value.value.@address; getLatLngByZyuusyo() } public function mouseMoveHandler(event:MouseEvent):void { var dragInitiator:Image=Image(event.currentTarget); var ds:DragSource = new DragSource(); ds.addData(dragInitiator, "img"); DragManager.doDrag(dragInitiator, ds, event); } private function dragEnterHandler(event:DragEvent):void { if (event.dragSource.hasFormat("img")){ DragManager.acceptDragDrop( UIComponent( event.currentTarget ) ); } } private var nowMarkerID:int; private var markerArr:Array = new Array(); private function dragDropHandler(event:DragEvent):void{ var bd:BitmapData = new BitmapData( 40,40,true,0x000000); bd.draw(Image(event.dragInitiator)); if(markerArr[Image(event.dragInitiator).name])return; var bm:Bitmap = new Bitmap( bd ); bm.filters = [gf]; var marker:Marker = new Marker( map.fromViewportToLatLng( new Point( myUI.mouseX,myUI.mouseY ) ), new MarkerOptions({ draggable :true, icon:bm, iconAlignment: MarkerOptions.ALIGN_HORIZONTAL_CENTER, hasShadow:true }) ); markerArr[Image(event.dragInitiator).name] = marker; var cnt:String = Image(event.dragInitiator).name; marker.addEventListener(MapMouseEvent.DRAG_END , function():void{ for( var i:int = 0 ; i < myXMLDATA.length() ; i ++ ){ if( myXMLDATA[i].id == cnt ){ tl.selectedIndex = i; myXMLDATA[i].lat = marker.getLatLng().lat(); myXMLDATA[i].lng = marker.getLatLng().lng(); htsFileUpdate.send({ "id":myXMLDATA[i].id, "lat":myXMLDATA[i].lat, "lng":myXMLDATA[i].lng }); } } }); marker.addEventListener(MapMouseEvent.CLICK , function():void{ nowMarkerID = int( cnt ); }); // marker.openInfoWindow( new InfoWindowOptions({content:Image(event.dragInitiator).source})); map.addOverlay(marker); // Image(event.dragInitiator).x = UIComponent(event.currentTarget).mouseX; // Image(event.dragInitiator).y = UIComponent(event.currentTarget).mouseY; } private function onHtsFileListResultHandler(e:Event):void{ myXMLDATA = htsFileList.lastResult.item; for( var i:int = 0 ; i < myXMLDATA.length() ; i ++ ){ if( myXMLDATA[i].lat != "" && myXMLDATA[i].lng != "" ){ if(markerArr[myXMLDATA[i].id])return; var loader:Loader = new Loader(); loader.name = "" + i + "-" + myXMLDATA[i].id; loader.contentLoaderInfo.addEventListener(Event.COMPLETE , function(e:Event):void{ var myBitmap:Bitmap = Bitmap(LoaderInfo(e.currentTarget).content); myBitmap.width = 40; myBitmap.height = 40; myBitmap.filters = [gf]; var myI:int = int( String( LoaderInfo(e.currentTarget).loader.name ).split("-")[0]); var myId:int = int( String( LoaderInfo(e.currentTarget).loader.name ).split("-")[1]); var marker:Marker = new Marker( new LatLng( myXMLDATA[myI].lat , myXMLDATA[myI].lng ) , new MarkerOptions({ draggable :true, icon:myBitmap, iconAlignment: MarkerOptions.ALIGN_HORIZONTAL_CENTER, hasShadow:true }) ); marker.addEventListener(MapMouseEvent.CLICK , function():void{ nowMarkerID = int( myId ); }); marker.addEventListener(MapMouseEvent.DRAG_END , function():void{ for( var i:int = 0 ; i < myXMLDATA.length() ; i ++ ){ if( myXMLDATA[i].id == myId ){ tl.selectedIndex = i; myXMLDATA[i].lat = marker.getLatLng().lat(); myXMLDATA[i].lng = marker.getLatLng().lng(); htsFileUpdate.send({ "id":myXMLDATA[i].id, "lat":myXMLDATA[i].lat, "lng":myXMLDATA[i].lng }); } } }); markerArr[myId] = marker; map.addOverlay(marker); }); loader.load( new URLRequest( myXMLDATA[i].image ) ); } } } private function onTlItemClickHander(e:Event):void{ if( tl.selectedItem.lat != "" && tl.selectedItem.lng != "" ){ map.panTo(new LatLng(tl.selectedItem.lat,tl.selectedItem.lng)); } } ]]> </mx:Script> <mx:GlowFilter id="gf" color="0xffffff" blurX="4" blurY="4" strength="10"/> <!--############ ############--> <mx:HTTPService id="htsFileList" url="http://moeten.info/flex/20081202_tripGoogleMap/?mode=filelist" resultFormat="e4x" result="onHtsFileListResultHandler(event)" /> <mx:HTTPService id="htsFileUpdate" url="http://moeten.info/flex/20081202_tripGoogleMap/?mode=fileupdate" resultFormat="e4x" method="GET" result="onHtsFileListResultHandler(event)" /> <mx:HTTPService id="htsZip" url="http://moeten.info/flex/20080502_twitterAir/myproxy.php?u=http://zip.cgis.biz/xml/zip.php" resultFormat="e4x" result="onHtsZipResultHandler(event)"/> <mx:HTTPService id="htsZyuusyo" url="http://moeten.info/flex/20080502_twitterAir/myproxy.php?u=http://zip.cgis.biz/xml/zip.php" resultFormat="e4x"/> <!--############ ############--> <mx:UIComponent id="myUI" width="500" height="536" x="10" y="115" dragEnter="dragEnterHandler(event);" dragDrop="dragDropHandler(event);" /> <mx:Label x="10" y="5" text="photo2map" fontSize="30" fontWeight="bold" color="0x999999"/> <mx:HRule x="10" y="48" width="888" height="8"/> <mx:HRule x="10" y="659" width="888" height="8"/> <mx:Label x="832" y="25" text="version 0.1" color="0x999999"/> <mx:TileList id="tl" x="518" y="115" height="536" width="380" backgroundAlpha="0.2" dataProvider="{myXMLDATA}" itemClick="onTlItemClickHander(event)" itemRenderer="myDataList"/> <mx:Canvas x="518" y="60" width="380" height="47" cornerRadius="5" borderColor="0x999999" borderStyle="solid" borderThickness="2" backgroundColor="0xffffff" dropShadowEnabled="true" backgroundAlpha="0.8"> <mx:Button x="179" y="8" label="画像追加" click="fileSelect()" width="97" height="25"/> <mx:Button x="284" y="8" label="リスト更新" click="{htsFileList.send()}" width="82" height="25"/> </mx:Canvas> <mx:Canvas x="10" y="60" width="500" height="47" cornerRadius="5" borderColor="0x999999" borderStyle="solid" borderThickness="2" backgroundColor="0xffffff" dropShadowEnabled="true" backgroundAlpha="0.8"> <mx:Button x="387" y="10" label="住所から検索" width="99" click="getLatLngByZyuusyo()"/> <mx:Button x="119" y="10" label="郵便番号から検索" click="getLatLngByZipcode()"/> <mx:TextInput id="zyuusyoTxt" x="239" y="10" text="東京都千代田区" width="140"/> <mx:TextInput id="yuubin1Txt" x="10" y="10" width="33" text="101"/> <mx:TextInput id="yuubin2Txt" x="66" y="10" width="45" text="0022"/> <mx:Label x="51" y="12" text="-"/> </mx:Canvas> <mx:Label x="232" y="675" text="簡単な説明:右の画像リストを地図へドラッグしてね。右クリックからの削除とかはうまくいかないけど気にしない!"/> </mx:Application>
PHP部分のソースはこちら
<?php ini_set("upload_max_filesize","5M"); /******************************************************* 常用マイ関数 *******************************************************/ function d() { echo '<pre style="background:#fff;color:#333;border:1px solid #ccc;margin:2px;padding:4px;font-family:monospace;font-size:12px">'; foreach (func_get_args() as $v) var_dump($v); echo '</pre>'; } function h($str){ if(is_array($str)){ return array_map( "h",$str ); }else{ return htmlspecialchars($str,ENT_QUOTES); } } function e($str){ if(is_array($str)){ return array_map( "e" , $str ); }else{ return mysql_real_escape_string( $str ); } } /******************************************************* DB設定 *******************************************************/ $username = ""; $password = ""; $dbhostname= ""; $dbname = ""; //DBへ接続 $dbh = mysql_connect( $dbhostname , $username, $password ) or die ('I cannot connect to the database because: ' . mysql_error() ); $dbh_s = mysql_select_db( $dbname ); /******************************************************* メイン *******************************************************/ if( $_GET['mode'] == "fileupload" ){ $image = file_get_contents( $_FILES['Filedata']['tmp_name'] ); $image_e = e( $image ); //DBに入れる $sql = " INSERT INTO flex_tripgooglemap( image, adate, print )VALUES( '{$image_e}', CURRENT_TIMESTAMP, '1' );"; $result = mysql_query( $sql ); $lastid = mysql_insert_id(); file_put_contents( "image/{$lastid}.jpg" , $image ); exit; }elseif( $_GET['mode'] == "filelist" ){ //DBリスト $xml = <<<EOD <result> EOD; $sql = " SELECT * , DATE_FORMAT(mdate,'%Y/%m/%d') as mydate , DATE_FORMAT(mdate,'%k:%i:%s') as mytime FROM flex_tripgooglemap WHERE print = '1' ORDER BY id DESC "; $result = mysql_query( $sql ); while( $val = mysql_fetch_assoc( $result ) ){ $xml .= <<<EOD <item> <id>{$val['id']}</id> <image>http://moeten.info/flex/20081202_tripGoogleMap/image/{$val['id']}.jpg</image> <mdate>{$val['mdate']}</mdate> <mydate>{$val['mydate']}</mydate> <mytime>{$val['mytime']}</mytime> <adate>{$val['adate']}</adate> <title>{$val['title']}</title> <comment>{$val['comment']}</comment> <lat>{$val['lat']}</lat> <lng>{$val['lng']}</lng> <print>{$val['print']}</print> </item> EOD; } $xml .= <<<EOD </result> EOD; header ("Content-Type: text/xml; charset=UTF-8"); echo $xml; exit; }elseif( $_GET['mode'] == "fileupdate" && $_GET['id'] != "" ){ $id = e( $_GET['id'] ); $lat = e( $_GET['lat'] ); $lng = e( $_GET['lng'] ); if( $_GET['clear'] != "" ){ $lat = ""; $lng = ""; } $sql = " UPDATE flex_tripgooglemap SET lat = '{$lat}' , lng = '{$lng}' WHERE id = '{$id}' LIMIT 1 "; $result = mysql_query( $sql ); //DBの更新 /* id, image, mdate, title, comment, lat, lng, print */ exit; } ?>