使用 Typeahead.js returns 无搜索城市

Searching cities using Typeahead.js returns nothing

我有一个 table places 具有这些字段

id, country_code, postal_code, place_name, admin_name1, admin_code1, admin_name2, admin_code2, admin_name3, admin_code3, latitude, longitude, accuracy

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

到目前为止,return在开发者控制台中没有任何错误。

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

Warning: preg_split(): Unknown modifier '/' in /home/jharvard/vhosts/localhost/public/pset8_new/public/search.php on line 9

Warning: array_map(): Argument #2 should be an array in /home/jharvard/vhosts/localhost/public/pset8_new/public/search.php on line 9

Warning: array_search() expects parameter 2 to be array, null given in /home/jharvard/vhosts/localhost/public/pset8_new/public/search.php on line 11

Warning: Cannot modify header information - headers already sent by (output started at /home/jharvard/vhosts/localhost/public/pset8_new/public/search.php:11) in /home/jharvard/vhosts/localhost/public/pset8_new/public/search.php on line 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>

错误消息告诉您第 9 行的 preg_split 中有一个 "unknown modifier '/'"。查看第 9 行的 preg_split

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

我假设您正在尝试用空格、换行符或逗号分隔地址?如果是这样,您将使用错误类型的斜线转义它们。要转义正则表达式中的字符,您需要使用反斜杠,因此:

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