使用Typeahead.js搜索城市不会返回任何内容

时间:2016-03-23 12:16:17

标签: php jquery typeahead.js

我有一个包含这些字段的表places

  

id,country_code,postal_code,place_name,admin_name1,admin_code1,   admin_name2,admin_code2,admin_name3,admin_code3,纬度,   经度,准确度

我有一个带有搜索输入字段的谷歌地图,如果我搜索"密歇根"它应该列出密歇根州所有的城镇和城镇的邮政编码,如果我点击一个,它应该带我到地图上的那个地方。

到目前为止,它在开发人员的控制台中没有返回任何错误。

但是,如果我直接转到http://localhost/pset8_new/public/search.php?geo=Cambridge+MA它应该返回具有适当结果的JSON代码,而是我得到这些错误

  

警告:preg_split():未知的修饰符' /'在   /home/jharvard/vhosts/localhost/public/pset8_new/public/search.php on   第9行

     

警告:array_map():参数#2应该是一个数组   /home/jharvard/vhosts/localhost/public/pset8_new/public/search.php on   第9行

     

警告:array_search()期望参数2为数组,null中给出null   /home/jharvard/vhosts/localhost/public/pset8_new/public/search.php on   第11行

     

警告:无法修改标头信息 - 已发送的标头   (输出始于   /home/jharvard/vhosts/localhost/public/pset8_new/public/search.php:11)   在/home/jharvard/vhosts/localhost/public/pset8_new/public/search.php中   在第98行

我在这里缺少什么?

这是search.php

<?php

    require(__DIR__ . "/../includes/config.php");

    // numerically indexed array of places
    $places = [];

    // TODO: search database for places matching $_GET["geo"], store in $places
    $params = array_map("trim", preg_split("/[/ \n/,]+/", $_GET["geo"]));
    // remove "US" param
    if (($index = array_search("US", $params)) !== false) {
        unset($params[$index]);
    }

    $search = [];
    $cityFound = 0;
    $stateFound = 0;
    $zipFound = 0;

    for ( $n = 0; $n < count($params); $n++ ) 
    {
        //if only digits => set id zip 
        if (is_numeric($params[$n])) 
        { 
            $search['zip'] = $params[$n];
            $zipFound = 1;
        }

        // if two letters => set id state 
        elseif ( strlen($params[$n]) === 2 ) 
        { 
            // compare with the the table
            $state = query("SELECT admin_name1 FROM places WHERE admin_code1 = (?) LIMIT 1", $params[$n]);
            // if match was found change to full name
            if ($state)
            {
                // change array with corresponding state full name
                $search['state'] = $state[0]['admin_name1'];
                $stateFound = 1;
            }
         }

        // if match against admin_name1 => state
        elseif ( strlen($params[$n]) > 2)
        {
            // compare with the the table -> state
            $state = query("SELECT admin_name1 FROM places WHERE admin_name1 = (?) LIMIT 1", $params[$n]); 

            // if match was found change to full name
            if ($state)
            {
                // change array with corresponding state full name
                $search['state'] = $params[$n];
                $stateFound = 1;
            }

            // compare with the the table city
            $city = query("SELECT place_name FROM places WHERE place_name = (?) LIMIT 1", $params[$n]);
            // if match was found set key <- city
            if ($city)
            {
                $search['city'] = $params[$n];
                $cityFound = 1;
            }
        }      
    }

    // if zip found
    if ($zipFound === 1)
    {
        // put the array back together using implode().
        $query = $search['zip'];
        // Search across multiple columns
        $places = query("SELECT * FROM places WHERE MATCH(postal_code, place_name, admin_name1, admin_code1) AGAINST (?)", $query);
    }

    // if only only city or state found
    elseif ($cityFound + $stateFound === 1)
    {
        // put the array back together using implode().
        $query = implode(" ", $search);
        // Search across multiple columns
        $places = query("SELECT * FROM places WHERE MATCH(postal_code, place_name, admin_name1, admin_code1) AGAINST (?)", $query);
    }

    // if city and state found
    elseif ($cityFound + $stateFound === 2)
    {
        // Search across multiple columns
        $places = query("SELECT * FROM places WHERE place_name = ? AND admin_name1 = ?", $search['city'], $search['state']);
    }   

    //foreach ($rows as $value)
    //{
      //  array_push($places, $value);
    //}
    // output places as JSON (pretty-printed for debugging convenience)
    header("Content-type: application/json");
    print(json_encode($places, JSON_PRETTY_PRINT));

?>

这是script.js

function configure()
{
    // update UI after map has been dragged
    google.maps.event.addListener(map, "dragend", function() {
        update();
    });

    // update UI after zoom level changes
    google.maps.event.addListener(map, "zoom_changed", function() {
        update();
    });

    // remove markers whilst dragging
    google.maps.event.addListener(map, "dragstart", function() {
        removeMarkers();
    });

    // configure typeahead
    // https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md
    $("#q").typeahead({
        autoselect: true,
        highlight: true,
        minLength: 1
    },
    {
        source: search,
        templates: {
            empty: "no places found yet",
            suggestion: _.template("<p><span id='place_name'><%- place_name %>,</span> <span id='admin_name1'><%- admin_name1 %></span> <span id='postal_code'><%- postal_code %></span></p>")
        }
    });


    // re-center map after place is selected from drop-down
    $("#q").on("typeahead:selected", function(eventObject, suggestion, name) {

        // ensure coordinates are numbers
        var latitude = (_.isNumber(suggestion.latitude)) ? suggestion.latitude : parseFloat(suggestion.latitude);
        var longitude = (_.isNumber(suggestion.longitude)) ? suggestion.longitude : parseFloat(suggestion.longitude);

        // set map's center
        map.setCenter({lat: latitude, lng: longitude});

        // update UI
        update();
    });

    // hide info window when text box has focus
    $("#q").focus(function(eventData) {
        hideInfo();
    });

    // re-enable ctrl- and right-clicking (and thus Inspect Element) on Google Map
    // https://chrome.google.com/webstore/detail/allow-right-click/hompjdfbfmmmgflfjdlnkohcplmboaeo?hl=en
    document.addEventListener("contextmenu", function(event) {
        event.returnValue = true; 
        event.stopPropagation && event.stopPropagation(); 
        event.cancelBubble && event.cancelBubble();
    }, true);

    // update UI
    update();

    // give focus to text box
    $("#q").focus();
}

/**
 * Removes markers from map.
 */
function removeMarkers(){
    for(var i = 0; i < markers.length;i++){
        markers[i].setMap(null);
        markers[i].length = 0;
    }    
}

/**
 * Searches database for typeahead's suggestions.
 */
function search(query, cb){
    // get places matching query (asynchronously)
    var parameters = {
        geo: query
    };
    $.getJSON("search.php", parameters)
    .done(function(data, textStatus, jqXHR) {

        // call typeahead's callback with search results (i.e., places)
        //console.log(data);
        cb(data);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {

        // log error to browser's console
        console.log(errorThrown.toString());
    });
}

这是index.html              

        <!-- https://developers.google.com/maps/documentation/javascript/tutorial -->
        <div id="map-canvas"></div>

        <!-- http://getbootstrap.com/css/#forms -->
        <form class="form-inline" id="form" role="form">
            <div class="form-group">
                <label class="sr-only" for="q">City, State, Postal Code</label>
                <input class="form-control" id="q" placeholder="City, State, Postal Code" type="text"/>
            </div>
        </form>
    </div>

1 个答案:

答案 0 :(得分:1)

错误消息告诉您第9行的preg_split中有“未知修饰符'/'”。请查看第9行的preg_split

$params = array_map("trim", preg_split("/[/ \n/,]+/", $_GET["geo"]));

我假设你试图用空格,新行或逗号分割地址?如果是这样,你用错误类型的斜线逃脱这些。要转义正则表达式中的字符,您需要使用反斜杠,所以:

$params = array_map("trim", preg_split("/[\ \n\,]+/", $_GET["geo"]));