将Google地图上的图形多边形保存到mysql中

时间:2019-05-09 10:17:32

标签: php mysql google-maps

我有一些问题,希望有人帮我解决。问题是:

1)我想将图形多边形保存到数据库mysql中。 2)每个多边形可以具有不同的名称并插入数据库。 3)编辑并删除已创建的多边形,并将其保存到数据库中。

在我的代码中,我正在使用Google Map工具绘制和给在Google Map上绘制的每个多边形赋予颜色。所以我希望有人帮助我编写有关将所有这些保存到数据库的代码。谢谢

代码。

protected boolean tapButton(List<MobileElement> element, int sec) {
    boolean isSuccess;
    setTiming(sec);
    isSuccess = tap(element);
    setDefaultTiming();
    return isSuccess;
}

public synchronized void setTiming(int sec) {
    PageFactory.initElements(new AppiumFieldDecorator(driver, Duration.ofSeconds(sec)), this);
}

public synchronized void setDefaultTiming() {
    PageFactory.initElements(new AppiumFieldDecorator(driver, Duration.ofSeconds(20)), this);
}

// Part of the method, not sure if it's important
public boolean tap(MobileElement el) {
    TapOptions tapOptions;
    ...
    for (int j = 0; j < 2; j++) {
        try {
            tapOptions = new TapOptions().withElement(ElementOption.element(el));
            new TouchAction(driver).tap(tapOptions).perform();
            result = true;
            break;
        } catch (Exception e) {
            ...
        }
    }
    ...
}   

1 个答案:

答案 0 :(得分:0)

好吧,考虑到问题的广泛性质以及缺乏支持结构/资源,如果以下各项满足您的需要,则需要学习和适应。

第一步是创建所需的数据库结构-在这里,我在名为gm_polygons的新数据库中创建了两个非常基本的mySQL表。我并不是说这些模式足以满足您需要存储在表中的所有数据(例如颜色,笔触,标题等)的需要,但是会提供一个起点。

create table `paths` (
    `id` int(10) unsigned not null auto_increment,
    `pid` int(10) unsigned not null default '0',
    `lat` float not null default '0',
    `lng` float not null default '0',
    primary key (`id`),
    index `pid` (`pid`)
)
collate='utf8_general_ci'
engine=innodb;


create table `polygon` (
    `id` int(10) unsigned not null auto_increment,
    `name` varchar(50) not null default '0',
    primary key (`id`)
)
collate='utf8_general_ci'
engine=innodb;

php映射页面。地图加载(在这种情况下,以伦敦为中心),并为该地图分配了一个侦听器,该地图允许绘制多边形(此演示中仅包含多边形,没有圆或多段线等)-表单具有用于输入poly和一个按钮,通过ajax将详细信息发送到php脚本进行处理。

您可以在生成此处显示的数据库和表之后,通过添加主机,用户,密码等的相关详细信息来修改以下内容,然后运行此文件进行测试。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();


        /* process the addition of the polygon */
        if( !empty( $_POST['name'] ) && !empty( $_POST['path'] ) ){


            $dbhost =   'localhost';
            $dbuser =   'root'; 
            $dbpwd  =   'xxx'; 
            $dbname =   'gm_polygons';
            $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );


            $name=$_POST['name'];
            $path=json_decode( $_POST['path'] );



            /* insert new path */
            $sql='insert into polygon set `name`=?';
            $stmt=$db->prepare( $sql );

            if( !$stmt )exit( 'Error: query 1' );

            $stmt->bind_param('s',$name);
            $stmt->execute();
            $stmt->free_result();
            $stmt->close();


            /* get the ID for the newly inserted Polygon name */
            $id=$db->insert_id;




            /* add all the latlng pairs for the polygon */
            $sql='insert into `paths` ( `pid`, `lat`, `lng` ) values ( ?, ?, ? )';
            $stmt=$db->prepare( $sql );

            if( !$stmt )exit( 'Error: query 2' );

            $stmt->bind_param( 'idd', $id, $lat, $lng );

            foreach( $path as $obj ){
                $lat=$obj->lat;
                $lng=$obj->lng;
                $stmt->execute();
            }
            $stmt->close();

            echo json_encode(
                array(
                    'name'=>$name,
                    'points'=>count($path)
                )
            );

        }
        exit();
    }
?>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Google Maps: Storing Polygons in database</title>
        <script async defer src='//maps.google.com/maps/api/js?key=APIKEY-gFJ0&callback=initMap&region=GB&language=en'></script>
        <script>

            let map;
            let div;
            let bttn;
            let input;
            let options;
            let centre;
            let poly;
            let path;
            let polypath;

            function initMap(){

                const ajax=function( url, params, callback ){
                    let xhr=new XMLHttpRequest();
                    xhr.onload=function(){
                        if( this.status==200 && this.readyState==4 )callback( this.response )
                    };
                    xhr.open( 'POST', url, true );
                    xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
                    xhr.send( buildparams( params ) );
                };
                const buildparams=function(p){
                    if( p && typeof( p )==='object' ){
                        p=Object.keys( p ).map(function( k ){
                            return typeof( p[ k ] )=='object' ? buildparams( p[ k ] ) : [ encodeURIComponent( k ), encodeURIComponent( p[ k ] ) ].join('=')
                        }).join('&');
                    }
                    return p;
                };
                const createpoly=function(){
                    poly=new google.maps.Polygon({
                      strokeColor: '#FF0000',
                      strokeOpacity: 0.8,
                      strokeWeight: 3,
                      fillColor: '#FF0000',
                      fillOpacity: 0.35,
                      draggable:true,
                      editable:true
                    });
                    poly.setMap( map );
                    return poly;
                };

                centre=new google.maps.LatLng( 51.483719, -0.020037 );
                div=document.getElementById('map');
                input=document.querySelector('#container > form > input[name="polyname"]');
                bttn=document.querySelector('#container > form > input[type="button"]');

                options = {
                    zoom: 15,
                    center: centre,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    disableDefaultUI: false,
                    mapTypeControl: true,
                    mapTypeControlOptions: {
                        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                        mapTypeIds: [ 'roadmap', 'terrain', 'satellite', 'hybrid' ]
                    }
                };
                map = new google.maps.Map( div, options );



                createpoly();



                google.maps.event.addListener( map, 'click', e=>{
                    path=poly.getPath();
                    path.push( e.latLng );
                });

                google.maps.event.addListener( poly, 'rightclick', e=>{
                    poly.setMap( null );
                    createpoly();
                });

                bttn.addEventListener('click',e=>{
                    if( input.value!='' ){

                        path=poly.getPath();
                        polypath=[];

                        for( let i=0; i < path.length; i++ ){
                            let point=path.getAt( i );
                            polypath.push( { lat:point.lat(), lng:point.lng() } )
                        }
                        let params={
                            path:JSON.stringify( polypath ),
                            name:input.value
                        }
                        let url=location.href;
                        let callback=function(r){
                            console.info( r );
                            input.value='';
                            poly.setMap( null );
                            createpoly();
                        };
                        /* send the polygon data */
                        ajax.call( this, url, params, callback );
                    }
                })
            }
        </script>
        <style>
            body{ background:white; }
            #container{
                width: 90%;
                min-height: 90vh;
                height:auto;
                box-sizing:border-box;
                margin: auto;
                float:none;
                margin:1rem auto;
                background:whitesmoke;
                padding:1rem;
                border:1px solid gray;
                display:block;
            }
            #map {
                width: 100%;
                height: 80%;
                clear:none;
                display:block;
                z-index:1!important;
                background:white;
                border:1px solid black;
            }
        </style>
    </head>
    <body>
        <div id='container'>
            <form method='post'>
                <input type='text' name='polyname' />
                <input type='button' value='Commit' title='Store the polygon' />
            </form>
            <div id='map'></div>
            <div id='data'></div>
        </div>
    </body>
</html>