如何更改 GooglePlacesAutocomplete 中的值

How to change value in GooglePlacesAutocomplete

如何更改此 GooglePlacesAutocomplete 的值?!

我想在更改地图上的标记位置时更改 googleplacesautocomplete 值。
我有机会只使用这个包。
也许您可以在不使用包中的第三方的情况下以某种方式更改值。
我有这个代码。

<Form.Item name="address">
   <GooglePlacesAutocomplete
    apiKey={API}
    apiOptions={{
    language: "ua",
    region: "ua",
    }}
         selectProps={{
             value,
             onChange: setValue,
             placeholder: "Select your address",
    }}
    name="address"
    value={value.label}
    />
</Form.Item>

完整代码:

import React, { useState, useCallback, useEffect } from "react";
import { GoogleMap, Marker, useJsApiLoader } from "@react-google-maps/api";
import { API } from "../../constants/map";
import Header from "../navigation/header";
import { createOffer } from "../../services/offerService";
import { getGoodCategories } from "../../services/goodCategoryService";
import { useHistory } from "react-router-dom";
import { inputValidationErrors } from "../../constants/messages/inputValidationErrors";
import { Form, Input, Button, DatePicker, AutoComplete, Select } from "antd";
import Geocode from "react-geocode";
import GooglePlacesAutocomplete, {
    geocodeByAddress,
    getLatLng,
} from "react-google-places-autocomplete";

Geocode.setApiKey(API);

Geocode.setLanguage("ua");

Geocode.setRegion("ua");

Geocode.enableDebug();

const { TextArea } = Input;
const { Option } = Select;

const containerStyle = {
    width: "100%",
    height: "100%",
};

const center = {
    lat: 50.643,
    lng: 26.263,
};

const defaultOptions = {
    panControl: true,
    zoomControl: true,
    zoomEnabled: true,
    mapTypeControl: true,
    disableDefaultUI: true,
    scaleControle: true,
    streetViewControl: true,
    rotateControl: true,
    clickableIcons: true,
    keyboardShortcuts: true,
    scrollwheel: true,
    fullscreenControl: true,
};

export default function Offer() {
    const { isLoaded } = useJsApiLoader({
        id: "google-map-script",
        googleMapsApiKey: API,
    });

    let history = useHistory();

    const [map, setMap] = useState();
    const [clickedLatLng, setClickedLatLng] = useState(center);
    const [data, setData] = useState(null);

    const [value, setValue] = useState("Rivne");
    const [coord, setCoord] = useState({ lat: 0, lng: 0 });

    const onLoad = useCallback(function callback(map) {
        const bounds = new window.google.maps.LatLngBounds(center);
        map.fitBounds(bounds);
        setMap(map);
    }, []);

    const onUnmount = useCallback(function callback(map) {
        setMap(null);
    }, []);

    const [form] = Form.useForm();

    const getData = (lat, lng) => {
        Geocode.fromLatLng(lat, lng).then(
            (response) => {
                const address = response.results[0].formatted_address;
                let settlement, region;
                for (
                    let i = 0;
                    i < response.results[0].address_components.length;
                    i++
                ) {
                    for (
                        let j = 0;
                        j <
                        response.results[0].address_components[i].types.length;
                        j++
                    ) {
                        switch (
                            response.results[0].address_components[i].types[j]
                        ) {
                            case "locality":
                                settlement =
                                    response.results[0].address_components[i]
                                        .long_name;
                                break;
                            case "administrative_area_level_1":
                                region =
                                    response.results[0].address_components[i]
                                        .long_name;
                                break;
                        }
                    }
                }

                //setValue(address);
                console.log("VALUE", value);

                form.setFieldsValue({
                    address: address,
                    settlement: settlement,
                    region: region,
                });
            },
            (error) => {
                console.error(error);
            }
        );
    };

    useEffect(async () => {
        setData(await getGoodCategories());
        if (value) {
            geocodeByAddress(value.label).then((result) => {
                getLatLng(result[0]).then((googleCoord) =>
                    setCoord(googleCoord)
                );
            });
        }
    }, [geocodeByAddress, getLatLng, value, setCoord]);

    console.log(coord.lat, coord.lng);

    const onFinish = (values) => {
        console.log(values);
        createOffer(values, clickedLatLng, history);
    };

    const onFinishFailed = (values) => {
        console.log("error");
    };

    return isLoaded ? (
        <>
            <Header />
            <div className="createOfferBody">
                <h1>Create offer</h1>
                <Form
                    form={form}
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    scrollToFirstError
                >
                    <div className="topFormBlock">
                        <div className="addressBlock">
                            <Form.Item name="address">
                                <GooglePlacesAutocomplete
                                    apiKey={API}
                                    apiOptions={{
                                        language: "ua",
                                        region: "ua",
                                    }}
                                    selectProps={{
                                        value,
                                        onChange: setValue,
                                        placeholder: "Select your address",
                                    }}
                                    name="address"
                                    value={value.label}
                                />
                            </Form.Item>
                            <Form.Item
                                name="settlement"
                                rules={[
                                    {
                                        type: "string",
                                        message:
                                            inputValidationErrors.EMPTY_SETTLEMENT_MESSAGE,
                                    },
                                    {
                                        required: true,
                                        message:
                                            inputValidationErrors.EMPTY_SETTLEMENT_MESSAGE,
                                    },
                                ]}
                            >
                                <Input
                                    name="settlement"
                                    placeholder="Enter your settlement"
                                />
                            </Form.Item>
                            <Form.Item
                                name="region"
                                rules={[
                                    {
                                        type: "string",
                                        message:
                                            inputValidationErrors.EMPTY_SETTLEMENT_MESSAGE,
                                    },
                                    {
                                        required: true,
                                        message:
                                            inputValidationErrors.EMPTY_SETTLEMENT_MESSAGE,
                                    },
                                ]}
                            >
                                <Input
                                    name="region"
                                    placeholder="Enter your settlement"
                                />
                            </Form.Item>
                        </div>

                        <div className="mapBlock">
                            <GoogleMap
                                mapContainerStyle={containerStyle}
                                center={center}
                                onLoad={onLoad}
                                onUnmount={onUnmount}
                                options={defaultOptions}
                                zoom={18}
                                onClick={(e) => setCoord(e.latLng.toJSON())}
                                    id="map"
                            >
                                <Marker
                                    position={coord}
                                    onPositionChanged={getData(
                                        coord.lat,
                                        coord.lng
                                    )}
                                    icon={{
                                        url: "https://cdn-icons-png.flaticon.com/512/6147/6147668.png",
                                        origin: new window.google.maps.Point(
                                            0,
                                            0
                                        ),
                                        anchor: new window.google.maps.Point(
                                            15,
                                            15
                                        ),
                                        scaledSize: new window.google.maps.Size(
                                            30,
                                            30
                                        ),
                                    }}
                                />
                            </GoogleMap>
                        </div>
                    </div>

                    <div className="bottomFormBlock">
                        <div className="otherOfferDataBlock">
                            <Form.Item name="goodCategoryId">
                                <Select>
                                    {data?.map((res, idx) => (
                                        <Option value={idx + 1} key={idx}>
                                            {res.name}
                                        </Option>
                                    ))}
                                </Select>
                            </Form.Item>

                            <Form.Item name="startDate">
                                <DatePicker />
                            </Form.Item>

                            <Form.Item
                                name="goodsWeight"
                                rules={[
                                    {
                                        message:
                                            inputValidationErrors.EMPTY_GOOD_WEIGHT_MESSAGE,
                                    },
                                    {
                                        required: true,
                                        message:
                                            inputValidationErrors.EMPTY_GOOD_WEIGHT_MESSAGE,
                                    },
                                ]}
                            >
                                <Input
                                    type="number"
                                    placeholder="Goods Weight"
                                />
                            </Form.Item>
                        </div>
                        <div className="otherOfferDataBlock">
                            <Form.Item
                                name="description"
                                className="description"
                                rules={[
                                    {
                                        message:
                                            inputValidationErrors.EMPTY_DESCRIPTION_MESSAGE,
                                    },
                                    {
                                        required: true,
                                        message:
                                            inputValidationErrors.EMPTY_DESCRIPTION_MESSAGE,
                                    },
                                ]}
                            >
                                <TextArea placeholder="Description" />
                            </Form.Item>

                            <Form.Item>
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    className="submitButton"
                                >
                                    Create offer
                                </Button>
                            </Form.Item>
                        </div>
                    </div>
                </Form>
            </div>
        </>
    ) : (
        <>
            <span>Map is not loaded!</span>
        </>
    );
}

如果您正在获取点击位置的地址,这看起来就像您在 getData 函数中所做的那样,请将地址传递给 setValue()。

const getData = (lat, lng) => {
    Geocode.fromLatLng(lat, lng).then(
        (response) => {
            const address = response.results[0].formatted_address;
            setValue(address)