Как я могу отобразить карту Google для города? - PullRequest
1 голос
/ 11 января 2012

Я пытаюсь отобразить карту Google, когда пользователь ищет город и нажимает кнопку поиска, но я не понимаю, как это сделать правильно.Вот мой код, сделанный до сих пор.Я не понимаю, как принять пользовательский ввод и проверить, что город находится в массиве.Если он находится в массиве, он должен отображаться на карте Google.Например, если пользователь вводит название города Хьюстон, США, оно должно отображаться на карте Google после проверки, находится ли название города в нашей базе данных.

Сценарий:

function searchResult(cityname) { 
    var namesOfCity = ["houston,boston,newyork,florida"];

    //check the user input 

    //if match display it on google map    
}

function initialize() 
{
        if(GBrowserIsCompatible()) {
            var map = new GMap2(document.getElementById("map"));
            map.setCenter(new GLatLng(37.4419, -122.1419), 13);
            map.setUIToDefault();
        }
    }

HTML

<body onload="initialize()" onunload="GUnload()">


 <input type="text" id="cityname" value="" name=""/>
  <input id="search" type="button" value="Search" onclick="searchResult('cityname')" />
  <div id="map" style="width: 100%; height: 450px; position: relative; background-color: rgb(229, 227, 223);"></div>

</body>

Ответы [ 2 ]

2 голосов
/ 11 января 2012

Вашему массиву нужно больше кавычек, чтобы каждый индекс представлял собой собственную строку:

//instead of using the inline click handler, this will bind a click event handler to your search button
$('#search').bind('click', searchResults);

//this is the click event handler for the search button
function searchResult(event) {

    //stop the default behavior of the button
    event.preventDefault();

    //cache whitelist of cities and the city that the user typed into the input
    var namesOfCity   = ["houston", "boston", "newyork", "florida"],
        inputValue    = $('#cityname').val().toLowerCase(),//notice the input has been made lower-case to attempt to match it to an index in the namesOfCity array
        inputAccepted = false;

    //iterate through the array of accepted city names
    for (var i = 0, len = namesOfCity.length; i < len; i++) {

        //check if the current index is equal to user's input
        if (inputValue == namesOfCity[i]) {

            //if the current index is equal to the user's input then set a flag to show that fact and stop the loop from iterating any further
            inputAccepted = true;
            break;
        }
    }

    //if match display it on google map
    if (inputAccepted === true) {
        //update the map here
    }   
}

Сервис геокодирования Google можно использовать для преобразования названия города в координаты долготы / широты: http://code.google.com/apis/maps/documentation/geocoding/ (я позволю вам поэкспериментировать с этими инструкциями)

1 голос
/ 11 января 2012

Вы близки, но неправильно инициализируете свой массив.

Вы также не сохраняете правильные координаты для каждого города в вашем массиве.

Вместо этого попробуйте использовать пользовательский объект для хранения названий разрешенных городов и их координат (широта и долгота) и посмотрите на это, чтобы определить, что отображать:

function searchResult(cityname) { 
    var cities = {
        houston: { 
           lat: /* ... */,
           long: /* ... */
        },
        boston: { 
           lat: /* ... */,
           long: /* ... */
        },
        'new york': { // note the quotes due to a space in the name
           lat: /* ... */,
           long: /* ... */
        },
        florida: { 
           lat: /* ... */,
           long: /* ... */
        }
    };

    //check the user input 
    var textfield = document.getElementById(cityname);

    if (textfield) {
        // look up the lowercase version of the value typed in
        var coords = cities[textfield.value.toLowerCase()];
        //if match display it on google map   
        if (coords) {
            var map = new GMap2(document.getElementById("map"));
            map.setCenter(new GLatLng(coords.lat, coords.long), 13); // you could also make the zoom level a property of each city, which would allow you to customise that per city
            map.setUIToDefault();
        }
    }     
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...