S
S
Sergey2020-12-11 20:10:04
Yandex maps
Sergey, 2020-12-11 20:10:04

How to show the user's entire city on the map in react-yandex-maps?

There is a map, you need to determine the user's city when loading the page and scale the map so that it fits all.

import React from "react";
import { YMaps, Map, Placemark, GeolocationControl } from "react-yandex-maps";

class LocationMap extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      coordinates: null,
      center: [ 0, 0 ],
    }

}
  
  onLoadMap(instance) {
    console.log(instance);
    const location = instance.geolocation.get();
    console.log(location);
  }

  onBoundsChange = e => {
    this.setState({
      center: e.get('target').getCenter(),
    });
    
    this.props.newCoordinates(e.get('target').getCenter());
  }

  render() {
    const coordinates = this.props.coords;
    const mapData = {
      center: coordinates || [55.684758, 37.738521],
      zoom: 17,
      behaviors: ["default", "scrollZoom"],
      controls: [],
      yandexMapDisablePoiInteractivity: false,
    };

    const mapOptions = {
      iconLayout: "default#image",
      iconImageHref: mapIcon,
      iconImageSize: [30, 42],
      iconImageOffset: [-3, -42],
    };

    return (
      <YMaps query={{apikey: 'key' }}>
        <Map
          defaultState={mapData}
          onLoad={(instance) => this.onLoadMap(instance)}
          modules={["geolocation", "geocode"]}
          instanceRef={this.props.instanceRef}
          onBoundsChange={this.onBoundsChange}
        >
          { [coordinates].map((coordinate) => (
              <Placemark
                geometry={coordinate}
                key={coordinate}
                options={mapOptions}
                draggable={false}
              />
            )) }
          <GeolocationControl options={{ position: {bottom: 50, right: 30} }} />
        </Map>
      </YMaps>
    );
  }
}

export default LocationMap;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question