从PHP调用JS文件中的JS函数

时间:2015-10-16 17:22:43

标签: javascript php jquery google-maps

我尝试使用javascript将标记添加到谷歌地图,但我生成的信息(从数据库收集TBD)。

我的index.php文件包含Mapper.js脚本,其中包含谷歌地图和将标记添加到地图的功能。

php代码生成一些虚假商店并尝试使用echo $ store-> markerJS();

将它们添加到地图中
// generates the script code to make a google map marker
public function markerJS(){
    $s = '<script type="text/javascript">addMarker('.$this->id.",".$this->lat.",".$this->long.");</script>";
    return $s;
}

Mapper.js在...... / js /

里面
var markers;
var map;
var bounds;

function initialize() {


    if (!(map === undefined)) {
        map = new google.maps.Map(document.getElementById('map-canvas'), {
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        markers = [];
        bounds = new google.maps.LatLngBounds();
    }


    var defaultLoc = new google.maps.LatLng(47.8258663, -122.30983839999999);
    var defaultLoc2 = new google.maps.LatLng(47.7752851, -122.3448616);
    bounds.extend(defaultLoc);
    bounds.extend(defaultLoc2);
    map.fitBounds(bounds);

    var marker = new google.maps.Marker({
        map: map,
        title: "Costco Lynwood",
        position: new google.maps.LatLng(47.8258663, -122.30983839999999)
    });

    markers.push(marker);

    // Create the search box and link it to the UI element.
    var input = /** @type {HTMLInputElement} */
            (
                    document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var searchBox = new google.maps.places.SearchBox(
            /** @type {HTMLInputElement} */ (input));

    // Listen for the event fired when the user selects an item from the
    // pick list. Retrieve the matching places for that item.
    google.maps.event.addListener(searchBox, 'places_changed', function () {

        var places = searchBox.getPlaces();

        for (var i = 0, marker; marker = markers[i]; i++) {
            marker.setMap(null);
        }

        markers = [];
        bounds = new google.maps.LatLngBounds();

        for (var i = 0, place; place = places[i]; i++) {


            // Create a marker for each place.
            var marker = new google.maps.Marker({
                map: map,
                title: place.name,
                position: place.geometry.location,
                addr: place.formatted_address
            });

            markers.push(marker);
            bounds.extend(place.geometry.location);


        }
        map.fitBounds(bounds);
        printMarkers(markers);


    });
}

google.maps.event.addDomListener(window, 'load', initialize);


function printMarkers() {

    for (var i = 0; i < markers.length; i++) {
        console.log("Marker " + i + ", Location: " + markers[i].addr);
    }
    console.log("End of print");
}


function addMarker(id, latitude, longitude) {

    console.log("Trying to add " + id + " to the map");
    //alert("Adding marker " + id);
    if (map === undefined) {
        console.log("Made a new map")
        map = new google.maps.Map(document.getElementById('map-canvas'), {
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        markers = [];
        bounds = new google.maps.LatLngBounds();
    }else {
        console.log("Map defined now adding")
    }



    var latlng = {lat: latitude, lng: longitude};

    var marker = new google.maps.Marker({
        map: map,
        title: id,
        position: latlng
    });

    markers.push(marker);
    bounds.extend(latlng);
    map.fitBounds(bounds);



}


function printTo(st) {
    $('#jsOutput').text(st);
}

index.php(主页)

<html>


    <head>
        <link rel="shortcut icon" href="">

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="js/libs/jquery/jquery.js"></script>
        <script type="text/javascript" src="js/libs/jqueryui/jquery-ui.js"></script>
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>      

        <link type="text/css" rel="stylesheet" href="css/basecss.css">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="map-canvas"></div>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <script type="text/javascript" src="js/Mapper.js"></script>
    <div id="jsOutput">JS Output</div>


    <?php
    // put your code here
    include_once "php/Store.php";
    // Some fake markers
    $stores = [];
    // [store ID, storeTemp, outsideTemp, energy, moneyPerHour], lat, long
    $stores[0] = new Store(["526", 75, 35, 100, 20], 43.612326, -79.690479);
    $stores[1] = new Store(["510", 75, 35, 100, 20], 44.09399, -79.489758);
    $stores[2] = new Store(["524", 75, 35, 100, 20], 43.622682, -79.507152);
    $stores[3] = new Store(["512", 75, 35, 100, 20], 43.406692136925, -80.391798020282);
    $stores[4] = new Store(["535", 75, 35, 100, 20], 43.730669, -79.456223);

    foreach($stores as $s){
        echo $s." -- Adding to google maps<br>";

        // addMarker(id, latitude, longitude) JS 
        echo $s->markerJS();
    }               

    ?>
    </body>
</html>

CSS

    /* 
    Document   : basecss
    Author     : nb
    Description: styles used by jQuery accordion widget
*/

root { 
    display: block;
}


/* jQuery accordion styles
----------------------------------*/
.ui-accordion { width: 100%; }
.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; margin-bottom: 0; background: #eee;}
.ui-accordion .ui-accordion-li-fix { display: inline; }
.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; }
.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .3em .5em .3em .7em; }
.ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; }
.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 20%; margin-top: -8px; }
.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 1px; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; zoom: 1; }
.ui-accordion .ui-accordion-content-active { display: block; }



/* Component containers
----------------------------------*/
.ui-widget { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; }
.ui-widget .ui-widget { font-size: 1em; }
.ui-widget-content { border: 1px solid #b81900; background: #eeeeee; color: #333333; border-top: 0;}
.ui-widget-content a { color: #333333; }
.ui-widget-header { border: 2px solid #000000; font-weight: normal; }



/* Interaction states
----------------------------------*/
.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; background: #f6f6f6; font-weight: bold; color: #1c94c4; }
/* color of header here */
.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #000000; text-decoration: none; }
.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #fbcb09; background: #fdf5ce; font-weight: bold;color: #c77405; }
.ui-state-hover a, .ui-state-hover a:hover { color: #c77405; text-decoration: none; }
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #b81900; background: #fffff3; font-weight: bold; color: #eb8f00; }
.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #eb8f00; text-decoration: none; }
.ui-widget :active { outline: none; }

body {
  margin: 0;
  padding: 0;
  font: 12px sans-serif;
}
h1, p {
  margin: 0;
  padding: 0;
}

#map-canvas {
    float: left;
    height:400px;
    width:600px;
}
#jsOutput {
    float: right;
    margin-left: 200px;
}

#phpOutput {
    float: bottom;
    margin: 20px 20px 20px 20px;
}
.controls {
    margin-top: 16px;
    border: 1px solid transparent;
    border-radius: 2px 0 0 2px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    height: 32px;
    outline: none;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
    background-color: #fff;
    padding: 0 11px 0 13px;
    width: 400px;
    font-family: Roboto;
    font-size: 15px;
    font-weight: 300;
    text-overflow: ellipsis;
}
#pac-input:focus {
    border-color: #4d90fe;
    margin-left: -1px;
    padding-left: 14px;
    /* Regular padding-left + 1. */
    width: 401px;
}
.pac-container {
    font-family: Roboto;
}
#type-selector {
    color: #fff;
    background-color: #4d90fe;
    padding: 5px 11px 0px 11px;
}
#type-selector label {
    font-family: Roboto;
    font-size: 13px;
    font-weight: 300;
}

php代码正在调用javascript中的函数,但它不是在地图上添加或显示标记吗?

我也遇到了一个奇怪的错误Uncaught TypeError: a.lat is not a function

2 个答案:

答案 0 :(得分:0)

这是不可能的。您的JavaScript代码在浏览器中的用户计算机上运行。您的PHP代码在服务器上运行。

答案 1 :(得分:0)

好的,我能够解决问题。由于代码问题是由于google.maps.event.addDomListener(window, 'load', initialize);

而在创建Google地图之前正在执行PHP脚本生成

我的修复是添加一个存储要添加的标记数组的全局变量,因此当页面准备就绪时,它可以添加标记。

继承我的Mapper.js

var markers;
var map;
var bounds;
var ready = false;
var toAddMarkers = [];

function initialize() {



    map = new google.maps.Map(document.getElementById('map-canvas'), {
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    markers = new Array();
    bounds = new google.maps.LatLngBounds();

//    var defaultLoc = new google.maps.LatLng(28.7, -127.5);
//    var defaultLoc2 = new google.maps.LatLng(48.85, -55.9);
//    bounds.extend(defaultLoc);
//    bounds.extend(defaultLoc2);
//    map.fitBounds(bounds);


    toAddMarkers.forEach(function (element, index, array) {

        console.log("Element @ " + index);
        console.log(element);
        var la = element["lat"];
        var lo = element["long"];
        var id = element["id"];

        console.log("id: " + id + "lat: " + la + "long: " + lo )

        //var latlng = {lat: la, lng: lo};
        var latlng = new google.maps.LatLng(la, lo);

        var marker = new google.maps.Marker({
            map: map,
            title: id,
            position: latlng
        });

        markers.push(marker);
        bounds.extend(latlng);
        map.fitBounds(bounds);

    });



    ready = true;

    // Create the search box and link it to the UI element.
    var input = /** @type {HTMLInputElement} */
            (
                    document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);


    var searchBox = new google.maps.places.SearchBox(
            /** @type {HTMLInputElement} */ (input));




    // Listen for the event fired when the user selects an item from the
    // pick list. Retrieve the matching places for that item.
    google.maps.event.addListener(searchBox, 'places_changed', function () {

        console.log("Search disabled");

        return;

        var places = searchBox.getPlaces();

        for (var i = 0, marker; marker = markers[i]; i++) {
            marker.setMap(null);
        }

        markers = [];
        bounds = new google.maps.LatLngBounds();

        for (var i = 0, place; place = places[i]; i++) {


            // Create a marker for each place.
            var marker = new google.maps.Marker({
                map: map,
                title: place.name,
                position: place.geometry.location,
                addr: place.formatted_address
            });

            markers.push(marker);
            bounds.extend(place.geometry.location);


        }
        map.fitBounds(bounds);
        printMarkers(markers);


    });


}

google.maps.event.addDomListener(window, 'load', initialize);


function printMarkers() {

    for (var i = 0; i < markers.length; i++) {
        console.log("Marker " + i + ", Location: " + markers[i].addr);
    }
    console.log("End of print");
}


function addMarker(id, latitude, longitude) {

    if (!ready) {
        console.log("1 - toAddMarkers");
        //alert("Adding marker " + id);
        var marker = [];
        marker["id"] = id;
        marker["lat"] = latitude;
        marker["long"] = longitude;
        toAddMarkers.push(marker);
    } else {
        console.log("2 - addMarker");
        var latlng = {lat: latitude, lng: longitude};

        var marker = new google.maps.Marker({
            map: map,
            title: id,
            position: latlng
        });

        markers.push(marker);
        bounds.extend(latlng);
        map.fitBounds(bounds);
    }


}


function printTo(st) {
    $('#jsOutput').text(st);
}

和我的index.php文件

<html>


    <head>
        <link rel="shortcut icon" href="">

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="js/libs/jquery/jquery.js"></script>
        <script type="text/javascript" src="js/libs/jqueryui/jquery-ui.js"></script>
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>      

        <link type="text/css" rel="stylesheet" href="css/basecss.css">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
         <div id="map-canvas"></div>
        <input id="pac-input" class="controls" type="text" placeholder="Search Box">
        <script type="text/javascript" src="js/Mapper.js"></script>
        <div id="jsOutput">JS Output</div>

        <div id="phpOutput">PHP</div>

        <?php

        // put your code here
        include_once "php/Store.php";
        // Some fake markers
        $stores = [];
        // [store ID, storeTemp, outsideTemp, energy, moneyPerHour], lat, long
        $stores[0] = new Store(["526", 75, 35, 100, 20], 43.612326, -79.690479);
        $stores[1] = new Store(["510", 75, 35, 100, 20], 44.09399, -79.489758);
        $stores[2] = new Store(["524", 75, 35, 100, 20], 43.622682, -79.507152);
        $stores[3] = new Store(["512", 75, 35, 100, 20], 43.406692136925, -80.391798020282);
        $stores[4] = new Store(["535", 75, 35, 100, 20], 43.730669, -79.456223);

        foreach($stores as $s){
            echo $s." -- Adding to google maps<br>";
            //echo var_dump($s);
            // addMarker(id, latitude, longitude) JS 
            echo $s->markerJS();
        }               

        ?>
    </body>
</html>