简体   繁体   English

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

[英]Calling JS Function in a JS File from PHP

Im attempting to add markers to a google map using javascript, but the information I have is generated (TBD collected from a database). 我试图使用javascript将标记添加到Google地图,但是生成了我所拥有的信息(从数据库中收集的TBD)。

My index.php file includes the Mapper.js script which contains the google map and functions to add the markers to the map. 我的index.php文件包含Mapper.js脚本,该脚本包含google地图和将标记添加到地图的功能。

The php code generates some fake stores and attempts to add them to the map using the echo $store->markerJS(); 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 inside .../js/ ... / js /中的Mapper.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 (main page) 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 的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;
}

The php code is correctly calling the function in the javascript but it isnt adding or displaying the markers on the map? php代码在javascript中正确调用了该函数,但未在地图上添加或显示标记?

I also get a weird error Uncaught TypeError: a.lat is not a function 我也收到一个奇怪的错误Uncaught TypeError: a.lat is not a function

This is impossible. 这是不可能的。 Your JavaScript code runs on the user's machine in their browser. 您的JavaScript代码在用户的浏览器中的计算机上运行。 Your PHP code runs on the server. 您的PHP代码在服务器上运行。

Ok i was able to make a work around. 好吧,我能够解决这个问题。 Since the problem with the code was that the PHP script generation was being executed before the google maps was created due to the google.maps.event.addDomListener(window, 'load', initialize); 由于该代码的问题是由于google.maps.event.addDomListener(window, 'load', initialize);而在创建Google地图之前执行了PHP脚本生成google.maps.event.addDomListener(window, 'load', initialize);

My fix was to add a global variable which stores an array of markers to be added, so when the page is ready to go, it can then add the markers. 我的解决方法是添加一个全局变量,该变量存储要添加的标记数组,因此,在页面准备就绪时,可以添加标记。

Heres my Mapper.js 这是我的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);
}

and my index.php file 和我的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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM