автозаполнение карт Google, не удается разрешить ввод, потому что автозаполнение добавляет символы юникода вместо текста - PullRequest
0 голосов
/ 03 ноября 2019

Итак, у меня есть веб-система такси с пружинной загрузкой, пользователь должен заполнить 2 поля: «от» и «куда идти», затем я конвертирую эти адреса в latlng и нахожу маршрут между ними. до этого момента все работало нормально, поэтому, когда я набираю адрес, он автоматически заполняется дополнительной информацией, такой как город и страна (раньше это было то же самое, работало нормально, но теперь не работает, использует украинский язык и каким-то образом конвертирует украинские буквы),и эта информация преобразуется в некоторые символы, такие как:

исходный ввод: 'вулиця Миколи Оводова, Винница, Винницкая область, Украина', целевой ввод: 'проспект Космонавтов, 53, Винница, Винницкая область, Україна». это какие типы ввода, то в приложении я получаю это:

вулиця Миколи Оводова, Вінниця, Вінницька область, Україна

Что я могу сделать по этому поводу? Мне нужен точно такой же ввод, как этот: 'проспект Космонавтов, 53, Винница, Винницкая область, Украина', не символы Юникода

Код, который у меня есть:

 @PostMapping(value = "/processInput", produces = "text/html")
    public String getOriginAndDestFromUser(@RequestParam String origin, @RequestParam String destination, Model model) throws IOException, ApiException, InterruptedException {
        model.addAttribute("origin", origin);
        model.addAttribute("destination", destination);
        model.addAttribute("cars", carService.findAll());
        model.addAttribute("carLocations", CarCoordinatsUtils.getCoords());

        String originPlaceId = getGeocodeCoordinates(origin);
        String destPlaceId = getGeocodeCoordinates(destination);
        model.addAttribute("originPlaceId", originPlaceId);
        model.addAttribute("destPlaceId", destPlaceId);

        return PagesConstants.RESPONSE_PAGE;
 public static String getGeocodeCoordinates(String address) throws InterruptedException, ApiException, IOException {
        GeocodingApiRequest request = GeocodingApi.newRequest(getGeoContext()).address(address);
        GeocodingResult result = request.await()[0];
        return result.geometry.location.toString();

    }

карта JavaScript. html:

<script>
    // This example requires the Places library. Include the libraries=places
    // parameter when you first load the API. For example:
    // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 49.2331, lng: 28.4682},
            zoom: 13
        });
        var card = document.getElementById('pac-card');
        var input = document.getElementById('pac-input');
        var dest = document.getElementById('pac-dest');
        var types = document.getElementById('type-selector');
        var strictBounds = document.getElementById('strict-bounds-selector');

        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);

        var autocomplete = new google.maps.places.Autocomplete(input);
        var autocomplete2 = new google.maps.places.Autocomplete(dest);

        // Bind the map's bounds (viewport) property to the autocomplete object,
        // so that the autocomplete requests use the current map bounds for the
        // bounds option in the request.
        autocomplete.bindTo('bounds', map);

        // Set the data fields to return when the user selects a place.
        autocomplete.setFields(
            ['address_components', 'geometry', 'icon', 'name']);

        var infowindow = new google.maps.InfoWindow();
        var infowindowContent = document.getElementById('infowindow-content');
        infowindow.setContent(infowindowContent);
        var marker = new google.maps.Marker({
            map: map,
            anchorPoint: new google.maps.Point(0, -29)
        });



        autocomplete.addListener('place_changed', function() {
            infowindow.close();
            marker.setVisible(false);
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                // User entered the name of a Place that was not suggested and
                // pressed the Enter key, or the Place Details request failed.
                window.alert("No details available for input: '" + place.name + "'");
                return;
            }

            // If the place has a geometry, then present it on a map.
            if (place.geometry.viewport) {
                map.fitBounds(place.geometry.viewport);
            } else {
                map.setCenter(place.geometry.location);
                map.setZoom(17);  // Why 17? Because it looks good.
            }
            marker.setPosition(place.geometry.location);
            marker.setVisible(true);

            var address = '';
            if (place.address_components) {
                address = [
                    (place.address_components[0] && place.address_components[0].short_name || ''),
                    (place.address_components[1] && place.address_components[1].short_name || ''),
                    (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
            }

            infowindowContent.children['place-icon'].src = place.icon;
            infowindowContent.children['place-name'].textContent = place.name;
            infowindowContent.children['place-address'].textContent = address;
            infowindow.open(map, marker);
        });

        // Sets a listener on a radio button to change the filter type on Places
        // Autocomplete.
        function setupClickListener(id, types) {
            var radioButton = document.getElementById(id);
            radioButton.addEventListener('click', function() {
                autocomplete.setTypes(types);
            });
        }

        setupClickListener('changetype-all', []);
        setupClickListener('changetype-address', ['address']);
        setupClickListener('changetype-establishment', ['establishment']);
        setupClickListener('changetype-geocode', ['geocode']);

        document.getElementById('use-strict-bounds')
            .addEventListener('click', function() {
                console.log('Checkbox clicked! New state=' + this.checked);
                autocomplete.setOptions({strictBounds: this.checked});
            });
    }
    var infoWindow = new google.maps.InfoWindow;

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);
        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());

    }

    function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
            'Error: The Geolocation service failed.' :
            'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
    }
</script>

Response.html

<script>
    var map;
    var start = document.getElementById("start");
    var end = document.getElementById("end");
    var origin = document.getElementById("origin").innerText;
    var destination = document.getElementById("destination").innerText;
    var originPlaceId = document.getElementById("originPlaceId").innerText;
    var destPlaceId = document.getElementById("destPlaceId").innerText;
    initMap();
    function initMap() {
        var directionsService = new google.maps.DirectionsService();
        var directionsRenderer = new google.maps.DirectionsRenderer();



        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 12,
            center: {lat: 49.2331, lng: 28.4682},
        });
        directionsRenderer.setMap(map);

        var onChangeHandler = function() {
            console.log('goes to here 1');
            calculateAndDisplayRoute(directionsService, directionsRenderer);
        };
        document.getElementById('showDirection').addEventListener('click', onChangeHandler);
    }

    function calculateAndDisplayRoute(directionsService, directionsRenderer) {
        console.log('goes to here 2');
        directionsService.route(
            {
                 origin: {query: document.getElementById("originPlaceId").innerText}, //45.65676020,-122.60382060
                 destination: {query: document.getElementById("destPlaceId").innerText}, //49.22513880,28.41919540//var end doesnt work here and request not found, should pass ltn and lng of start and dest and works fine
                //origin : {query: "49.2261393,28.4103459"},
                //destination : {query: "49.2250969,28.4187825"},
                travelMode: 'DRIVING'
            },
            function(response, status) {
                if (status === 'OK') {
                    console.log('goes to here 3');
                    directionsRenderer.setDirections(response);

                } else {
                    console.log('goes to here fail');
                    window.alert('Directions request failed due to ' + status);
                }
            });
    }
</script>

1 Ответ

0 голосов
/ 03 ноября 2019

Что происходит, так это то, что по каким-то причинам ваш параметр экранируется от HTML. Вы можете удалить его обратно, используя класс org.apache.commons.text.StringEscapeUtils из библиотеки apache.commons / commons-text . Вот код, который делает трюк:

private static void testUrlEncoding() {
    String actual = "Kosmonavtiv Avenue, 66, &#1042;&#1110;&#1085;&#1085;&#1080;&#1094;&#1103;, &#1042;&#1110;&#1085;&#1085;&#1080;&#1094;&#1100;&#1082;&#1072; &#1086;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100;, &#1059;&#1082;&#1088;&#1072;&#1111;&#1085;&#1072;";
        String unescaped = StringEscapeUtils.unescapeHtml4(actual);
        System.out.println(unescaped);
}

И вывод:

Kosmonavtiv Avenue, 66, Вінниця, Вінницька область, Україна

Информация, найденная по адресу: Как отменить отображение символов HTML в Java?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...