Google地图未在DIV中显示

时间:2014-03-20 03:35:08

标签: javascript php google-maps google-maps-api-3

我有一个网页,用于映射一个区域并确定地址或点是否位于指定区域内但由于某种原因它不再出现,它曾经工作正常,它最近停止了我不要以为最近有任何改变。这是我的代码:

的index.php:

<?php
    include "polygon.php";
    $location=null;
    $location_name=null;
    $loc=null;
    if (isset($_GET['location_id']) && isset($_GET['location'])){
        $location=$_GET['location_id'];
        $location_name=$_GET['location'];
        $loc = Polygon::getLocation($location_name);
    }

    if (isset($_POST['location_id']) && isset($_POST['location'])){
        $location=$_POST['location_id'];
        $location_name=$_POST['location'];
        $loc = Polygon::getLocation($location_name);
    }

    if (!empty($_POST)) {
        Polygon::saveCoords ($_POST['coords'], $location);
    }

    $data   = Polygon::getCoords($location);

    $coords = null;

    if(false!=$data) {
        // parse data
        preg_match_all('/\((.*?)\)/', $data, $matches);

        $coords= $matches[1];
    }
?>
<!DOCTYPE>

<html>
    <head>

    <title>DP Dough Delivery Area</title>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

    <script type="text/javascript" src="js/polygon.js"></script>

    <script type="text/javascript">
    $(function(){

        // create map
        <?php 
            if ($loc!=null){
                echo 'var mapCenter=new google.maps.LatLng('.$loc['lat'].','.$loc['lng'].');';
            } else {
                echo 'var mapCenter=new google.maps.LatLng(38.989697,-76.93776);';
            }
            echo $loc['lat'].','.$loc['lng'];
        ?>

        var myOptions = {
            zoom: 12,
            center: mapCenter,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById('main-map'), myOptions);

        // holds verification addresses
        var verifiedAddresses = new Array();

        // now create geocoder for address<->lat/long
        var geocoder = new google.maps.Geocoder();

        // attached a polygon creator drawer to the map
        var creator = new PolygonCreator(map);

        // address as point button
        $('#addAddress').click(function(){
            var address = document.getElementById("addressInput").value;
            geocoder.geocode( { 'address': address}, function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                //map.setCenter(results[0].geometry.location);
                creator.pen.draw(results[0].geometry.location);
              } else {
                alert("Geocode was not successful for the following reason: " + status);
              }
            });
        });   

        // address as point button
        $('#checkAddress').click(function(){
            var address = document.getElementById("checkAddressInput").value;
            geocoder.geocode( { 'address': address}, function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                //map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
                verifiedAddresses.push(marker);
                if(null==creator.showData()){
                    $('#dataPanel').append('Please first create a polygon');
                }else{
                    data = creator.getPoints();
                    //alert(data);
                    var paths=creator.getPoly().getPlots();
                    var pt = paths.getAt(0);
                    var numPaths = pt.getLength();
                    var j=0;
                    var oddNodes = false;
                    var x = results[0].geometry.location.lng();
                    var y = results[0].geometry.location.lat();
                    for (var i=0; i < numPaths; i++) {
                      j++;
                      if (j == numPaths) {j = 0;}
                      if (((pt.getAt(i).lat() < y) && (pt.getAt(j).lat() >= y))
                      || ((pt.getAt(j).lat() < y) && (pt.getAt(i).lat() >= y))) {
                        if ( pt.getAt(i).lng() + (y - pt.getAt(i).lat())
                        /  (pt.getAt(j).lat()-pt.getAt(i).lat())
                        *  (pt.getAt(j).lng() - pt.getAt(i).lng())<x ) {
                          oddNodes = !oddNodes
                        }
                      }
                    }
                    if(oddNodes == true) {
                        alert("Address is VALID");
                        $('#dataPanel').append(address+': VALID ADDRESS');
                    } else {
                        alert("Address is INVALID");
                        $('#dataPanel').append(address+': INVALID ADDRESS');
                    }
                }
              } else {
                alert("Geocode was not successful for the following reason: " + status);
              }
            });
        });   

        // reset button
        $('#reset').click(function(){
            creator.destroy();
            creator=null;              
            creator=new PolygonCreator(map);  
            $.each(verifiedAddresses, function(index, value){
                value.setMap(null);
            });
            verifiedAddresses =null;
            verifiedAddresses =new Array();
            verifiedAddresses.length=0;                
        });   

        // set polygon data to the form hidden field
        $('#map-form').submit(function () {
            $('#map-coords').val(creator.showData());
        });

        //show coords
        $('#showData').click(function(){ 
            $('#dataPanel').empty();
            if(null==creator.showData()){
                $('#dataPanel').append('Please first create a polygon');
            }else{
                $('#dataPanel').append(creator.showData());
            }
        });

         //show color
        $('#showColor').click(function(){ 
            $('#dataPanel').empty();
            if(null==creator.showData()){
                $('#dataPanel').append('Please first create a polygon');
            }else{
                $('#dataPanel').append(creator.showColor());
            }
        });
        <?php if (null!=$coords): ?>
         // create
        var polygonCoords = [<?php
                                foreach ( $coords as $i=>$coord ):
                                    echo 'new google.maps.LatLng('.$coord.')';
                                    if ( $i<=count($coords)) {
                                     echo ',';
                                    }
                                endforeach;?>];

        $.each(polygonCoords, function(index, value){
            creator.pen.draw(value);
        });
        // construct the polygon
        polygon = new google.maps.Polygon({
                               paths: polygonCoords,
                               strokeColor: "#FF0000",
                               strokeOpacity: 0.8,
                               strokeWeight: 2,
                               fillColor: "#FF0000",
                               fillOpacity: 0.35
        });

        // show polygon on the map
        polygon.setMap(map);
        <?php endif;?>

    });
    </script>

    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div id="header">
        <p>
        <span class="instruction">Instructions:</span>
        Left click on the map to create markers, when last marker meets first marker, it will form a polygon.
        Right click on the polygon to change its hex value color.
        </p>
    </div>
    <div id="main-map">
    </div>
    <div id="side">
        <input id="addressInput"  placeholder="Add Address As Point " type="text" class="navi"/>
        <input id="addAddress" value="Add Address As Point" type="button" class="navi"/>
        <input id="checkAddressInput"  placeholder="Verify Address " type="text" class="navi"/>
        <input id="checkAddress" value="Verify Address" type="button" class="navi"/>
        <input id="reset" value="Reset" type="button" class="navi"/>
        <input id="showData"  value="Show Data Points " type="button" class="navi"/>
        <input id="showColor"  value="Show Color " type="button" class="navi"/>
        <div   id="dataPanel">
        </div>
    </div>
    <form action="index.php" method="POST" id="map-form">
        <input type="hidden" name="coords" id="map-coords" value=""/>
        <input type="hidden" name="location_id" id="location_id" value="<?php echo $location; ?>"/>
        <input type="hidden" name="location" id="location" value="<?php echo $location_name; ?>"/>
        <input type="submit" name="save" value="Save"/>
        <input type="button" value="Reset" id="reset"/>
    </form>
</body>
</html>

的style.css:

html,body{
    margin:0;
    padding:0;
    width:100%;
    height:100%;
    font-family:Arial, Helvetica, sans-serif;
}
div#header{    
    vertical-align:middle;
    border-bottom:1px solid #000;
}
div#main-map{
    width:70%;
    height:70%;
    float:left;
}
div#side{
    width:30%;
    float:left;
}

div#dataPanel{
    width:90%;
    height:50%;
    overflow:auto;
    border:2px solid #DDDDDD;
}
div#side input{
    width:90%;
}

div#side input.navi{
    font-size:18px;
    height:30px;
    margin-bottom:10px;
}
div ul{
    margin-top:30px;
    margin-bottom:30px;
}
div ul li{
    display: inline;
    list-style-type: none;
    padding-right: 40px;
    font-size:18px;
    font-weight:bold;
}

div ul li.title{
    font-size:22px;
    color:#888;
}

div#header p{
    color:#888;
    font-size:14px;
    padding-left:20px;
}
span.instruction{
    font-weight:bold;
}

.message-box { text-align: center; padding: 5px; color:#545454; width:80%;  margin:5px auto; font-size:12px;}
.clean { background-color: #efefef; border-top: 2px solid #dedede; border-bottom: 2px solid #dedede; }
.info  { background-color: #f7fafd; border-top: 2px solid #b5d3ff; border-bottom: 2px solid #b5d3ff; }
.ok    { background-color: #d7f7c4; border-top: 2px solid #82cb2f; border-bottom: 2px solid #82cb2f; }
.alert { background-color: #fef5be; border-top: 2px solid #fdd425; border-bottom: 2px solid #fdd425; }
.error { background-color: #ffcdd1; border-top: 2px solid #e10c0c; border-bottom: 2px solid #e10c0c; }

polygon.php:

<?php

class Polygon
{
    static $_dbHost     = 'localhost'; 
    static $_dbName     = 'database';   
    static $_dbUserName = 'root';  
    static $_dbUserPwd  = 'password';
    static private $url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=";

    static public function getLocation($address){
        $url = self::$url.urlencode($address);

        $resp_json = self::curl_file_get_contents($url);
        $resp = json_decode($resp_json, true);

        if($resp['status']='OK'){
            return $resp['results'][0]['geometry']['location'];
        }else{
            return false;
        }
    }

    static public function getLocationURL($address){
        $url = self::$url.urlencode($address);
        return $url;
    }

    static private function curl_file_get_contents($URL){
        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_URL, $URL);
        $contents = curl_exec($c);
        curl_close($c);

        if ($contents) return $contents;
            else return FALSE;
    }

    // get coordinates
    static public function getCoords($location)
    {
        if ($location == null) return FALSE;
        return self::get($location);
    }

    // save coordinates
    static public function saveCoords($rawData, $location)
    {
        self::save($rawData, $location);
    }

    static public function getLocationAddress($city)
    {
        $data=false;
        if ($city!=null && $city!=""){
            $link = mysqli_connect("localhost", "root", "password", "database");
            if ($stmt = $link->prepare("SELECT address FROM tbl_location_data WHERE city=?")) {
            /* bind parameters for markers */
            $sql= "SELECT address FROM tbl_location_data WHERE city=\"$city\"";
            if ($result = $link->query($sql)) {
                while($obj = $result->fetch_object()){
                    $data=$obj->address;
                }
                return $data;
            }  else {
                $stmt->bind_param("s", $city);
                /* execute query */
                $stmt->execute();
                /* bind result variables */
                $stmt->bind_result($data);
                /* fetch value */
                $stmt->fetch();
                /* close statement */
                            if ($stmt->num_rows <= 0)
                            {
                                $stmt->close();
                                return FALSE;
                            }    
                $stmt->close();
            }
        }

        return $data;
        }
    }

    // save lat/lng to database
    static public function save ($data, $location)
    {
        if($location!=null && !self::locationExists($location)){
            $link = mysqli_connect("localhost", "root", "password", "database");
            /* Create the prepared statement */
            if ($stmt = $link->prepare("INSERT INTO points (location_id, data) values (?, ?)")) {

                /* Bind our params */
                $stmt->bind_param('ss', $location, $data);

                /* Execute the prepared Statement */
                $stmt->execute();

                /* Echo results */
                echo "Inserted data into database<br>";

                /* Close the statement */
                $stmt->close();
            }
            else {
                /* Error */
                printf("Prepared Statement INSERT Error: %s\n", $mysqli->error);
            }
        } else if ($location!=null && self::locationExists($location)){
            $link = mysqli_connect("localhost", "root", "password", "database");
            /* Create the prepared statement */
            if ($stmt = $link->prepare("UPDATE points SET data=? WHERE location_id=?")) {

                /* Bind our params */
                $stmt->bind_param('ss', $data, $location);

                /* Execute the prepared Statement */
                $stmt->execute();

                /* Echo results */
                echo "UPDATED {$location},<br>{$data}<br> into database\n";

                /* Close the statement */
                $stmt->close();
            }
            else {
                /* Error */
                printf("Prepared Statement UPDATE Error: %s\n", $mysqli->error);
            }
        }
    }  

    static private function locationExists($location){
        $link = mysqli_connect("localhost", "root", "password", "database");
        /* Create the prepared statement */
        if ($stmt = $link->prepare("SELECT id FROM points WHERE location_id = ?")) {

            /* Bind our params */
            $stmt->bind_param('s', $location);

            /* Execute the prepared Statement */
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($id);
            $stmt->fetch();

            if ($stmt->num_rows > 0)
            {
                $stmt->close();
                return TRUE;
            }
            $stmt->close();
            return FALSE;
        }
    }

    // get lat/lng from database
    static private function get($location)
    {  
        $data   = false;
        $link = mysqli_connect("localhost", "root", "password", "database");
        /* Create the prepared statement */
        if ($stmt = $link->prepare("SELECT data FROM points WHERE location_id=?")) {
            /* bind parameters for markers */
            $sql= "SELECT id,data FROM points WHERE location_id=\"$location\"";
            if ($result = $link->query($sql)) {
                while($obj = $result->fetch_object()){
                    $data=$obj->data;
                }
                return $data;
            }  else {
                $stmt->bind_param("s", $location);
                /* execute query */
                $stmt->execute();
                /* bind result variables */
                $stmt->bind_result($data);
                /* fetch value */
                $stmt->fetch();
                /* close statement */
                            if ($stmt->num_rows <= 0)
                            {
                                $stmt->close();
                                return FALSE;
                            }    
                $stmt->close();
            }
        }

        return $data;
    }

}

polygon.js:

function PolygonCreator(map){
    //create pen to draw on map
    this.map = map;
    this.pen = new Pen(this.map);
    var thisOjb=this;
    this.event=google.maps.event.addListener(thisOjb.map, 'click', function(event) { 
                thisOjb.pen.draw(event.latLng);
    });

    this.showData = function(){
        return this.pen.getData();
    }

    this.getPoints = function(){
        return this.pen.getPlots();
    }

    this.showColor = function(){
        return this.pen.getColor();
    }

    this.getPoly = function() {
        return this.pen.getPolygon();
    }

    //destroy the pen
    this.destroy = function(){
        this.pen.deleteMis();
        if(null!=this.pen.polygon){
            this.pen.polygon.remove();
        }
        google.maps.event.removeListener(this.event);
    }
}    
/*
 * pen class
 */
function Pen(map){
    this.map= map;
    this.listOfDots = new Array();
    this.polyline =null;
    this.polygon = null;
    this.currentDot = null;
    //draw function
    this.draw = function(latLng){
        if (null != this.polygon) {
            alert('Click Reset to draw another');
        }else {
            if (this.currentDot != null && this.listOfDots.length > 1 && this.currentDot == this.listOfDots[0]) {
                this.drawPolygon(this.listOfDots);
            }else {
                //remove previous line
                if(null!=this.polyline){
                    this.polyline.remove();
                }
                //draw Dot
                var dot = new Dot(latLng, this.map, this);
                this.listOfDots.push(dot);
                //draw line
                if(this.listOfDots.length > 1){
                    this.polyline = new Line(this.listOfDots, this.map);
                }
            }
        }
    }
    //draw ploygon
    this.drawPolygon = function (listOfDots,color,des,id){
        this.polygon = new Polygon(listOfDots,this.map,this,color,des,id);
        this.deleteMis();
    }
    //return polygon
    this.getPolygon = function () {
        return this.polygon;
    }

    //delete all dots and polylines
    this.deleteMis = function(){
        //delete dots
        $.each(this.listOfDots, function(index, value){
            value.remove();
        });
        this.listOfDots.length=0;
        //delete lines
        if(null!=this.polyline){
            this.polyline.remove();
            this.polyline=null;
        }
    }
    //cancel
    this.cancel = function(){
        if(null!=this.polygon){
            (this.polygon.remove());
        }
        this.polygon=null;
        this.deleteMis();
    }
    //setter        
    this.setCurrentDot = function(dot){
        this.currentDot = dot;
    }
    //getter
    this.getListOfDots = function(){
        return this.listOfDots;
    }
    //get plots data
    this.getData = function(){
        if(this.polygon!=null){
            var data ="";
            var paths = this.polygon.getPlots();
            //get paths
            paths.getAt(0).forEach(function(value, index){
                data+=(value.toString());
            });
            return data;
        }else {
            return null;
        }
    }
    //get plots data
    this.getPlots = function(){
        if(this.polygon!=null){
            var paths = this.polygon.getPlots();

            return paths;
        }else {
            return null;
        }
    }
    //get color
    this.getColor = function(){
            if(this.polygon!=null){
                var color = this.polygon.getColor();
                return color;
            }else {
                return null;
            }

    }
}

/* Child of Pen class
 * dot class
 */
function Dot(latLng,map,pen){
    //property
    this.latLng=latLng;
    this.parent = pen;

    this.markerObj = new google.maps.Marker({
             position: this.latLng, 
             map: map
    }); 

    //closure
    this.addListener = function(){
            var parent=this.parent;
            var thisMarker=this.markerObj;
            var thisDot=this;
            google.maps.event.addListener(thisMarker, 'click', function() { 
               parent.setCurrentDot(thisDot);
                parent.draw(thisMarker.getPosition());
            });             
    }   
    this.addListener();

    //getter 
    this.getLatLng = function(){
            return this.latLng;
    }

    this.getMarkerObj = function(){
            return this.markerObj;
    }

    this.remove = function(){
        this.markerObj.setMap(null);
    }
}

/* Child of Pen class
 * Line class
 */
function Line(listOfDots,map){
    this.listOfDots = listOfDots;
    this.map = map;
    this.coords = new Array();
    this.polylineObj=null;

    if (this.listOfDots.length > 1) {
        var thisObj=this;
        $.each(this.listOfDots, function(index, value){
            thisObj.coords.push(value.getLatLng());
        });

        this.polylineObj  = new google.maps.Polyline({
         path: this.coords,
         strokeColor: "#FF0000",
         strokeOpacity: 1.0,
         strokeWeight: 2,
         map: this.map
       });
   }

    this.remove = function(){
        this.polylineObj.setMap(null);
    }
}

/* Child of Pen class
 * polygon class
 */
function Polygon(listOfDots,map,pen,color){
    this.listOfDots = listOfDots;
    this.map = map;
    this.coords = new Array();
    this.parent = pen;
    this.des = 'Hello';



    var thisObj=this;
    $.each(this.listOfDots,function(index,value){
        thisObj.coords.push(value.getLatLng());
    });

    this.polygonObj= new google.maps.Polygon({
               paths: this.coords,
               strokeColor: "#FF0000",
               strokeOpacity: 0.8,
               strokeWeight: 2,
               fillColor: "#FF0000",
               fillOpacity: 0.35,
                map:this.map
    });

    this.remove = function(){
        this.info.remove();
        this.polygonObj.setMap(null);
    }

    //getter
    this.getContent = function(){
        return this.des;
    }


    this.getPolygonObj= function(){
        return this.polygonObj;
    }

    this.getListOfDots = function (){
        return this.listOfDots;
    }

    this.getPlots = function(){
        return this.polygonObj.getPaths();
    }

    this.getColor=function(){
        return  this.getPolygonObj().fillColor;
    }

    //setter
    this.setColor = function(color){
        return  this.getPolygonObj().setOptions(
                        {fillColor:color,
                        strokeColor:color,
                        strokeWeight: 2
                        }
                    );
    }


    this.info = new Info(this,this.map);

    //closure       
    this.addListener = function(){
            var info=this.info;
            var thisPolygon=this.polygonObj;
            google.maps.event.addListener(thisPolygon, 'rightclick', function(event) {                  
               info.show(event.latLng);
            });             
    }   
    this.addListener();

}

/*
 * Child of Polygon class
 * Info Class
 */
function Info(polygon,map){
    this.parent = polygon;
    this.map = map;

    this.color =  document.createElement('input');

    this.button = document.createElement('input');
    $(this.button).attr('type','button');
    $(this.button).val("Change Color");
   var thisOjb=this;


    //change color action
    this.changeColor= function(){
        thisOjb.parent.setColor($(thisOjb.color).val());
    }

    //get content
    this.getContent = function(){
        var content = document.createElement('div');

        $(this.color).val(this.parent.getColor());  
        $(this.button).click(function(){
            thisObj.changeColor();
        });

        $(content).append(this.color);      
        $(content).append(this.button);
        return content;
    }

    thisObj=this;
    this.infoWidObj = new google.maps.InfoWindow({
               content:thisObj.getContent()
    });

    this.show = function(latLng){
        this.infoWidObj.setPosition(latLng);
        this.infoWidObj.open(this.map);
    }

    this.remove = function(){
        this.infoWidObj.close();
    }

}

我知道很多代码,但它的工作非常简单。 index.php中的get参数包含一个居中地图的位置和一个位置id,用于从数据库中抓取多边形点。然后创建多边形并将其覆盖在地图上,并检查地址是否有效地包含在多边形区域内或在多边形区域外无效。问题是地图没有显示在主映射div中,我不知道为什么停止工作,有人可能已经对代码进行了更改,但我似乎无法找到任何内容并且上次工作正常我做了任何修改。

1 个答案:

答案 0 :(得分:0)

这是一个愚蠢的错误,我没有注意到服务器管理员强制使用https而我正在通过http抓取脚本。我将保留此代码,因为它可能对其他人有用。谢谢