【问题标题】:google maps autocomplete, cannot resolver input because autocomplete adds unicode characters instead of text谷歌地图自动完成,无法解析输入,因为自动完成添加了 unicode 字符而不是文本
【发布时间】:2019-11-03 12:55:10
【问题描述】:

所以我有一个 Spring Boot 应用程序类型的出租车网络系统,用户必须填写 2 个字段:“从”和“去哪里”,然后我将这些地址转换为 latlng 并找到它们之间的路线。之前它工作正常,所以当我输入地址时,它会自动填充城市和国家等附加信息(以前是一样的,工作正常但现在它坏了,它使用乌克兰语并以某种方式转换乌克兰字母),并将此信息转换为一些符号,例如:

原点输入:'вулиця Миколи Оводова, Вінниця, Вінницька область, Україна', 目的地输入:'проспект Космонавтів, 53, Вінниця, Вінницька область, Україна'。 它是什么输入类型,然后在应用程序中我收到这个:

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

对此我能做些什么?我需要像这样完全相同的输入:'проспект Космонавтів, 53, Вінниця, Вінницька область, Україна' 不是 unicode 字符

我拥有的代码:

 @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 map.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>

响应.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>

【问题讨论】:

    标签: javascript java spring spring-boot google-maps


    【解决方案1】:

    发生的情况是,由于某种原因,您的参数被 HTML 转义。您可以使用库apache.commons/commons-text 中的类org.apache.commons.text.StringEscapeUtils 将其取消转义。下面是解决问题的代码:

    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, Вінниця, Вінницька область, Україна
    

    找到的信息:How to unescape HTML character entities in Java?

    【讨论】:

    • 它解码部分地址,比如街道和城市都可以,然后再次符号
    • like 'вулиця Миколи Оводова, Вінниця' 成功解码部分,然后再次 1074;улиця
    • 这有点奇怪,但是您可以在部分解码的字符串上再次运行相同的方法。看看之后它是否解码了第二部分......
    • 还是一样,街道没问题,城市和国家符号,很奇怪,因为我没有对应用程序的那部分做任何更改,突然停止工作
    • 请发布整个字符串 - 有问题的字符串和您期望的字符串
    猜你喜欢
    • 2017-03-01
    • 1970-01-01
    • 2019-01-25
    • 2014-11-24
    • 1970-01-01
    • 2016-11-17
    • 2018-01-26
    • 1970-01-01
    相关资源
    最近更新 更多