【问题标题】:React js google api suggestion AutocompleteService getPlacePredictions restriction to a specific state将 js google api 建议 AutocompleteService getPlacePredictions 限制为特定状态
【发布时间】:2020-06-16 10:00:43
【问题描述】:

我有以下组件,你给我一个地址。

问题是我需要你建议给我的地址来引用单个州。

有没有办法通过 API 指定这个限制?

或者您认为我可以通过代码来实现吗?

我以为我在里面做某事,你想让它认为这是正确的方法吗? 我有问题吗?

React.useEffect(() => {
    let active = true;
    if (!autocompleteService.current && window.google)
        autocompleteService.current = new window.google.maps.places.AutocompleteService();
    if (!autocompleteService.current) return undefined;
    if (value === '') {
        setOptions([]);
        return undefined;
    }
    fetch({ input: value }, res => {

        //edit
        const loc = res.map(a => (a.description.split(',').pop().trim() === 'Italia' ? a : false)).filter(Boolean);

        if (active) setOptions(loc || []);
    });
    return () => {
        active = false;
    };
}, [value, fetch]);

代码:

import React from 'react';
import { useTranslation } from 'react-i18next';
import { makeStyles, TextField, Grid, Typography } from '@material-ui/core';
import { Autocomplete } from '@material-ui/lab';
import { LocationOn } from '@material-ui/icons';
import parse from 'autosuggest-highlight/parse';
import throttle from 'lodash/throttle';

function loadScript(src, position, id) {
    if (!position) return;
    const script = document.createElement('script');
    script.setAttribute('async', '');
    script.setAttribute('id', id);
    script.src = src;
    position.appendChild(script);
}
const autocompleteService = { current: null };
const useStyles = makeStyles(theme => ({
    icon: {
        color: theme.palette.text.secondary,
        marginRight: theme.spacing(2)
    }
}));

export default function AutocompleteGoogleMaps(props) {
    const { api, value, onChange, changeinfo } = props;
    const classes = useStyles();
    const [options, setOptions] = React.useState([]);
    const loaded = React.useRef(false);

    const { i18n } = useTranslation();
    let language = localStorage.getItem('lang');
    if (language === null) language = i18n.language;

    if (typeof window !== 'undefined' && !loaded.current) {
        if (!document.querySelector('#google-maps')) {
            loadScript(
                `https://maps.googleapis.com/maps/api/js?key=${api}&libraries=places&language=${language}`,
                document.querySelector('head'),
                'google-maps'
            );
        }
        loaded.current = true;
    }

    const handleChange = ({ target: { value } }) => {
        onChange(value);
    };

    const onTagsChange = (event, val) => {
        if (val !== null && val.description !== null) {
            onChange({ target: { value: val.description } });
            if (changeinfo) geocodeByAddress(val.description).then(changeinfo);
        }
    };

    const fetch = React.useMemo(
        () =>
            throttle((input, callback) => {
                autocompleteService.current.getPlacePredictions(input, callback);
            }, 200),
        []
    );

    React.useEffect(() => {
        let active = true;
        if (!autocompleteService.current && window.google)
            autocompleteService.current = new window.google.maps.places.AutocompleteService();
        if (!autocompleteService.current) return undefined;
        if (value === '') {
            setOptions([]);
            return undefined;
        }
        fetch({ input: value }, res => {
            if (active) setOptions(res || []);
        });
        return () => {
            active = false;
        };
    }, [value, fetch]);

    const geocodeByAddress = address => {
        const geocoder = new window.google.maps.Geocoder();
        const { OK } = window.google.maps.GeocoderStatus;

        return new Promise((resolve, reject) => {
            geocoder.geocode({ address }, (results, status) => {
                if (status !== OK) {
                    return reject(status);
                }
                return resolve(results);
            });
        });
    };

    return (
        <Autocomplete
            id="google-map"
            getOptionLabel={option => (typeof option === 'string' ? option : option.description)}
            filterOptions={x => x}
            options={options}
            autoComplete
            includeInputInList
            freeSolo
            value={value}
            renderInput={params => <TextField {...params} onChange={handleChange} {...props} />}
            onChange={onTagsChange}
            renderOption={({
                structured_formatting: {
                    main_text_matched_substrings: matches,
                    main_text: city,
                    secondary_text: street
                }
            }) => {
                const parts = parse(
                    city,
                    matches.map(match => [match.offset, match.offset + match.length])
                );
                return (
                    <Grid container alignItems="center">
                        <Grid item>
                            <LocationOn className={classes.icon} />
                        </Grid>
                        <Grid item xs>
                            {parts.map(({ highlight, text }, key) => (
                                <span key={key} style={{ fontWeight: highlight ? 700 : 400 }}>
                                    {text}
                                </span>
                            ))}
                            <Typography variant="body2" color="textSecondary">
                                {street}
                            </Typography>
                        </Grid>
                    </Grid>
                );
            }}
        />
    );
}

【问题讨论】:

    标签: javascript reactjs google-maps google-places-api googleplacesautocomplete


    【解决方案1】:

    我们在 Google 问题跟踪器中为此功能请求提供了一个类似条目,以便我们可以向所有 Google Maps Platform API 用户提供有关它的信息,因为我们的许多客户都对这个问题的技术方面感兴趣,

    问题跟踪器中的问题和功能请求由 Places API 专家直接策划,只要工程团队有消息,他们就会在问题跟踪器中提供更新。

    我们诚挚地邀请您在问题跟踪器中查看该问题,并为其加注星标以注册您的兴趣。这将订阅您接收有关该问题的技术更新。为该问题加注星标还为我们提供了有关该问题对客户的重要性的宝贵反馈,并提高了产品工程团队对该问题的优先级。

    您可以在此处查看问题并加注星标:

    此问题跟踪器条目是有关此问题的公开信息的权威来源,所有公开相关的更新都将在此处发布。

    【讨论】:

    • 最后似乎有一个计策解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2019-09-03
    • 2014-10-13
    • 1970-01-01
    • 2013-04-23
    • 2016-06-22
    • 2017-08-05
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多