2015-10-16 96 views
0

我試圖使用JavaScript將標記添加到谷歌地圖,但生成的信息(從數據庫收集的TBD)。從PHP的JS文件中調用JS函數

我的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中的函數,但它不添加o r在地圖上顯示標記?

我也得到一個奇怪的錯誤Uncaught TypeError: a.lat is not a function

+0

請提供[最小的,完整的,經過測試和讀示例](http://stackoverflow.com/幫助/麥克風),證明了這個問題。 PHP無能爲力,只需瀏覽器就能看到。 – geocodezip

+0

問題是關於PHP爲什麼它不會幫助?我已經提供了除CSS之外的所有內容,現在已添加。 –

+0

因爲錯誤來自API,所以重新創建錯誤只需瀏覽器即可看到。我們無法運行PHP。 – geocodezip

回答

0

好吧,我能夠解決問題。由於代碼的問題在於,由於google.maps.event.addDomListener(window, 'load', initialize);

創建谷歌地圖之前正在執行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> 
0

這是不可能的。您的JavaScript代碼在用戶的瀏覽器中運行。您的PHP代碼在服務器上運行。

+0

這怎麼可能。我得到了php代碼來執行javascript中的函數,現在我遇到的唯一問題是php在Javascript中的initialize()函數之前執行。 –

+1

php是soley服務器端,它無法觸及你的javascript。 – Coz

+1

@Coz PHP可以生成JavaScript以在瀏覽器上運行。但這是它自己的概念。 –