Add search control to the map

Open in CodeSandbox

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
    <script crossorigin src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>
    <!-- To make the map appear, you must add your apikey -->
    <script src="https://js.api.mappable.world/v3/?apikey=<YOUR_APIKEY>&lang=en_US" type="text/javascript"></script>

    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="./common.ts"
    ></script>
    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="../variables.ts"
    ></script>
    <script data-plugins="transform-modules-umd" data-presets="typescript" type="text/babel">
      import type {SearchResponse} from '@mappable-world/mappable-types';
      import {LOCATION, MARGIN, initialMarkerProps} from '../variables';
      import {findSearchResultBoundsRange} from './common';

      window.map = null;

      main();
      async function main() {
        // Waiting for all api elements to be loaded
        await mappable.ready;
        const {MMap, MMapDefaultSchemeLayer, MMapDefaultFeaturesLayer, MMapControls} = mappable;

        const {MMapDefaultMarker, MMapSearchControl} = await mappable.import(
          '@mappable-world/mappable-default-ui-theme'
        );

        map = new MMap(document.getElementById('app'), {location: LOCATION, margin: MARGIN});

        map.addChild(new MMapDefaultSchemeLayer({}));
        map.addChild(new MMapDefaultFeaturesLayer({}));

        const initialMarker = new MMapDefaultMarker({
          title: initialMarkerProps.properties.name,
          subtitle: initialMarkerProps.properties.description,
          coordinates: initialMarkerProps.geometry.coordinates,
          size: 'normal',
          iconName: 'fallback',
          onClick: () => {
            map.removeChild(initialMarker);
          }
        });
        map.addChild(initialMarker);
        const searchMarkers = [initialMarker];

        const updateSearchMarkers = (searchResult: SearchResponse) => {
          searchMarkers.forEach((marker) => {
            map.removeChild(marker);
          });

          searchResult.forEach((element) => {
            const marker = new MMapDefaultMarker({
              title: element.properties.name,
              subtitle: element.properties?.description,
              coordinates: element.geometry.coordinates,
              size: 'normal',
              iconName: 'fallback',
              onClick: () => {
                map.removeChild(marker);
              }
            });
            map.addChild(marker);
            searchMarkers.push(marker);
          });
        };

        const updateMapLocation = (searchResult: SearchResponse) => {
          if (searchResult.length !== 0) {
            let center;
            let zoom;
            let bounds;

            if (searchResult.length === 1) {
              center = searchResult[0].geometry?.coordinates;
              zoom = 12;
            } else {
              bounds = findSearchResultBoundsRange(searchResult);
            }

            map.update({
              location: {
                center,
                zoom,
                bounds,
                duration: 400
              }
            });
          }
        };

        const searchResultHandler = (searchResult: SearchResponse) => {
          updateSearchMarkers(searchResult);
          updateMapLocation(searchResult);
        };

        map.addChild(
          new MMapControls({position: 'top'}).addChild(
            new MMapSearchControl({
              searchResult: searchResultHandler
            })
          )
        );
      }
    </script>

    <!-- prettier-ignore -->
    <style> html, body, #app { width: 100%; height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } .toolbar { position: absolute; z-index: 1000; top: 0; left: 0; display: flex; align-items: center; padding: 16px; } .toolbar a { padding: 16px; }  </style>
    <link rel="stylesheet" href="./common.css" />
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
    <script crossorigin src="https://cdn.jsdelivr.net/npm/react@17/umd/react.production.min.js"></script>
    <script crossorigin src="https://cdn.jsdelivr.net/npm/react-dom@17/umd/react-dom.production.min.js"></script>
    <script crossorigin src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>
    <!-- To make the map appear, you must add your apikey -->
    <script src="https://js.api.mappable.world/v3/?apikey=<YOUR_APIKEY>&lang=en_US" type="text/javascript"></script>

    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="./common.ts"
    ></script>
    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="../variables.ts"
    ></script>
    <script data-plugins="transform-modules-umd" data-presets="react, typescript" type="text/babel">
      import type {SearchResponse, Feature} from '@mappable-world/mappable-types';
      import {LOCATION, MARGIN, initialMarkerProps} from '../variables';
      import {findSearchResultBoundsRange} from './common';

      window.map = null;

      main();
      async function main() {
        // For each object in the JS API, there is a React counterpart
        // To use the React version of the API, include the module @mappable-world/mappable-reactify
        const [mappableReact] = await Promise.all([
          mappable.import('@mappable-world/mappable-reactify'),
          mappable.ready
        ]);
        const reactify = mappableReact.reactify.bindTo(React, ReactDOM);

        const {useState, useCallback} = React;

        const {MMap, MMapDefaultSchemeLayer, MMapDefaultFeaturesLayer, MMapControls} = reactify.module(mappable);

        const {MMapDefaultMarker, MMapSearchControl} = reactify.module(
          await mappable.import('@mappable-world/mappable-default-ui-theme')
        );

        ReactDOM.render(
          <React.StrictMode>
            <App />
          </React.StrictMode>,
          document.getElementById('app')
        );

        function App() {
          const [location, setLocation] = useState(LOCATION);
          const [searchMarkersProps, setSearchMarkersProps] = useState([initialMarkerProps]);

          const updateMapLocation = useCallback((searchResult: SearchResponse) => {
            if (searchResult.length !== 0) {
              let center;
              let zoom;
              let bounds;

              if (searchResult.length === 1) {
                center = searchResult[0].geometry?.coordinates;
                zoom = 12;
              } else {
                bounds = findSearchResultBoundsRange(searchResult);
              }

              setLocation({
                center,
                zoom,
                bounds,
                duration: 400
              });
            }
          }, []);

          const searchResultHandler = useCallback((searchResult: SearchResponse) => {
            setSearchMarkersProps(searchResult);
            updateMapLocation(searchResult);
          }, []);

          const onClickSearchMarkerHandler = useCallback(
            (clickedMarker: Feature) => {
              setSearchMarkersProps(searchMarkersProps.filter((marker) => marker !== clickedMarker));
            },
            [searchMarkersProps]
          );

          return (
            <MMap location={location} margin={MARGIN} ref={(x) => (map = x)}>
              <MMapDefaultSchemeLayer />
              <MMapDefaultFeaturesLayer />
              <MMapControls position="top">
                <MMapSearchControl searchResult={searchResultHandler} />
              </MMapControls>

              {searchMarkersProps.map((marker) => (
                <MMapDefaultMarker
                  key={+marker.geometry.coordinates}
                  title={marker.properties.name}
                  subtitle={marker.properties.description}
                  coordinates={marker.geometry.coordinates}
                  onClick={() => onClickSearchMarkerHandler(marker)}
                  size="normal"
                  iconName="fallback"
                />
              ))}
            </MMap>
          );
        }
      }
    </script>

    <!-- prettier-ignore -->
    <style> html, body, #app { width: 100%; height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } .toolbar { position: absolute; z-index: 1000; top: 0; left: 0; display: flex; align-items: center; padding: 16px; } .toolbar a { padding: 16px; }  </style>
    <link rel="stylesheet" href="./common.css" />
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
    <script crossorigin src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.js"></script>
    <script crossorigin src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>

    <script src="https://js.api.mappable.world/v3/?apikey=<YOUR_APIKEY>&lang=en_US" type="text/javascript"></script>

    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="./common.ts"
    ></script>
    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="../variables.ts"
    ></script>
    <script data-plugins="transform-modules-umd" data-presets="typescript" type="text/babel">
      import type {Feature, SearchResponse} from '@mappable-world/mappable-types';
      import {LOCATION, MARGIN, initialMarkerProps} from '../variables';
      import {findSearchResultBoundsRange} from './common';

      window.map = null;

      main();
      async function main() {
        // For each object in the JS API, there is a Vue counterpart
        // To use the Vue version of the API, include the module @mappable-world/mappable-vuefy
        const [mappableVue] = await Promise.all([mappable.import('@mappable-world/mappable-vuefy'), mappable.ready]);
        const vuefy = mappableVue.vuefy.bindTo(Vue);

        const {createApp, ref} = Vue;

        const {MMap, MMapDefaultSchemeLayer, MMapDefaultFeaturesLayer, MMapControls} = vuefy.module(mappable);

        const {MMapDefaultMarker, MMapSearchControl} = vuefy.module(
          await mappable.import('@mappable-world/mappable-default-ui-theme')
        );

        const app = createApp({
          components: {
            MMap,
            MMapDefaultSchemeLayer,
            MMapDefaultFeaturesLayer,
            MMapControls,
            MMapDefaultMarker,
            MMapSearchControl
          },
          setup() {
            const refMap = (ref: any) => {
              window.map = ref?.entity;
            };

            const location = ref(LOCATION);

            const searchMarkersProps = ref([initialMarkerProps]);

            const updateMapLocation = (searchResult: SearchResponse) => {
              if (searchResult.length !== 0) {
                let center;
                let zoom;
                let bounds;

                if (searchResult.length === 1) {
                  center = searchResult[0].geometry?.coordinates;
                  zoom = 12;
                } else {
                  bounds = findSearchResultBoundsRange(searchResult);
                }

                location.value = {
                  center,
                  zoom,
                  bounds,
                  duration: 400
                };
              }
            };

            const searchResultHandler = (searchResult: SearchResponse) => {
              searchMarkersProps.value = searchResult;
              updateMapLocation(searchResult);
            };

            const onClickSearchMarkerHandler = (clickedMarker: Feature) => {
              searchMarkersProps.value = searchMarkersProps.value.filter((marker) => marker !== clickedMarker);
            };

            return {location, MARGIN, refMap, searchResultHandler, searchMarkersProps, onClickSearchMarkerHandler};
          },
          template: `
            <MMap :location="location" :margin="MARGIN" :ref="refMap">
                <MMapDefaultSchemeLayer />
                <MMapDefaultFeaturesLayer />
                <MMapControls position="top">
                    <MMapSearchControl :searchResult="searchResultHandler" />
                </MMapControls>

                <MMapDefaultMarker
                    v-for="marker in searchMarkersProps"
                    :key="marker.geometry.coordinates"
                    :title="marker.properties.name"
                    :subtitle="marker.properties.description"
                    :coordinates="marker.geometry.coordinates"
                    :onClick="()=>onClickSearchMarkerHandler(marker)"
                    size="normal"
                    iconName="fallback"
                />
            </MMap>`
        });
        app.mount('#app');
      }
    </script>

    <!-- prettier-ignore -->
    <style> html, body, #app { width: 100%; height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } .toolbar { position: absolute; z-index: 1000; top: 0; left: 0; display: flex; align-items: center; padding: 16px; } .toolbar a { padding: 16px; }  </style>
    <link rel="stylesheet" href="./common.css" />
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
import type {LngLatBounds, SearchResponse} from '@mappable-world/mappable-types';

mappable.ready.then(() => {
  mappable.import.registerCdn('https://cdn.jsdelivr.net/npm/{package}', [
    '@mappable-world/mappable-default-ui-theme@0.0'
  ]);
});

export const findSearchResultBoundsRange = (searchResult: SearchResponse) => {
  let minLng: number | null = null;
  let maxLng: number | null = null;
  let minLat: number | null = null;
  let maxLat: number | null = null;

  searchResult.forEach((searchResultElement) => {
    const [lng, lat] = searchResultElement.geometry.coordinates;

    if (lng < minLng || minLng === null) {
      minLng = lng;
    }

    if (lng > maxLng || maxLng === null) {
      maxLng = lng;
    }

    if (lat < minLat || minLat === null) {
      minLat = lat;
    }

    if (lat > maxLat || maxLat === null) {
      maxLat = lat;
    }
  });

  return [
    [minLng, maxLat],
    [maxLng, minLat]
  ] as LngLatBounds;
};
import type {
  MMapLocationRequest,
  LngLatBounds,
  SearchResponse,
  Margin,
  Feature
} from '@mappable-world/mappable-types';

const BOUNDS: LngLatBounds = [
  [54.58311, 25.9985],
  [56.30248, 24.47889]
];
export const LOCATION: MMapLocationRequest = {bounds: BOUNDS};
export const MARGIN: Margin = [30, 30, 30, 30];

export const initialMarkerProps = {
  properties: {
    name: 'Dubai',
    description: 'United Arab Emirates'
  },
  geometry: {
    type: 'Point',
    coordinates: [55.289311, 25.229762]
  }
} as Feature;