leaflet#LatLng TypeScript Examples

The following examples show how to use leaflet#LatLng. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.ts    From project-tauntaun with GNU Lesser General Public License v3.0 7 votes vote down vote up
// Copied from https://github.com/gokertanrisever/leaflet-ruler
export function calculateBearing(from: LatLng, to: LatLng) {
  const f1 = from.lat;
  const l1 = from.lng;
  const f2 = to.lat;
  const l2 = to.lng;
  const toRadian = Math.PI / 180.0;

  // haversine formula
  const y = Math.sin((l2 - l1) * toRadian) * Math.cos(f2 * toRadian);
  const x =
    Math.cos(f1 * toRadian) * Math.sin(f2 * toRadian) -
    Math.sin(f1 * toRadian) * Math.cos(f2 * toRadian) * Math.cos((l2 - l1) * toRadian);
  let bearing = Math.atan2(y, x) * (180.0 / Math.PI);
  bearing += bearing < 0 ? 360.0 : 0.0;

  return bearing;
}
Example #2
Source File: SidcMarker.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function SidcMarker(props: SidcMarkerProps) {
  const { sidc, label, position } = props;
  const positionLatLng = position as LatLng;

  const { commanderMode } = AppStateContainer.useContainer();

  // prettier-ignore
  const memorizedItem = useMemo(() => <SidcMarkerNonMemo {...props} />, [
    sidc,
    label,
    positionLatLng.lat,
    positionLatLng.lng,
    commanderMode
  ]);

  return memorizedItem;
}
Example #3
Source File: map.component.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
private createMapOptions(latitude: number, longitude: number) {
    return {
      layers: [
        tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18 })
      ],
      zoom: 15,
      center: latLng(latitude, longitude),
      attributionControl: false,
    };
  }
Example #4
Source File: index.tsx    From aqualink-app with MIT License 6 votes vote down vote up
DashboardMap = ({ collection, classes }: DashboardMapProps) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("xs"));
  const [collectionCenter, collectionBounds] =
    getCollectionCenterAndBounds(collection);

  return (
    <Box className={classes.root}>
      <Map
        classes={{ map: classes.map }}
        initialCenter={collectionCenter || new LatLng(0, 0)}
        initialBounds={collectionBounds}
        initialZoom={3}
        collection={collection}
        showAlertLevelLegend={false}
        showWaterMark={false}
        geolocationEnabled={false}
        defaultLayerName="Heat Stress"
        legendBottom={isMobile ? 35 : 20}
        legendLeft={isMobile ? 2 : 4}
      />
    </Box>
  );
}
Example #5
Source File: siteUtils.ts    From aqualink-app with MIT License 6 votes vote down vote up
findInitialSitePosition = (
  sites: Site[],
  initialSiteId?: string
): LatLng | null => {
  const initialSite =
    (initialSiteId && findSiteById(sites, initialSiteId)) ||
    maxBy(
      sites,
      (site) =>
        `${site.collectionData?.tempWeeklyAlert || 0},${longDHW(
          site.collectionData?.dhw || null
        )}`
    );

  // If the polygon type is a Point, return its coordinates
  if (initialSite?.polygon.type === "Point") {
    return new LatLng(
      initialSite.polygon.coordinates[1],
      initialSite.polygon.coordinates[0]
    );
  }

  // If the polygon type is a Polygon, return the coordinates of its centroid
  if (initialSite?.polygon.type === "Polygon") {
    const centroidLat = meanBy(
      initialSite.polygon.coordinates[0],
      (coords) => coords[1]
    );
    const centroidLng = meanBy(
      initialSite.polygon.coordinates[0],
      (coords) => coords[0]
    );

    return new LatLng(centroidLat, centroidLng);
  }

  return null;
}
Example #6
Source File: map.ts    From aqualink-app with MIT License 6 votes vote down vote up
getCollectionCenterAndBounds = (
  collection?: CollectionDetails
): [LatLng | undefined, LatLngBounds | undefined] => {
  if (!collection) {
    return [undefined, undefined];
  }

  const coordinates = collection.sites.map((item) =>
    getMiddlePoint(item.polygon)
  );

  const center = new LatLng(
    meanBy(coordinates, (item) => item[1]),
    meanBy(coordinates, (item) => item[0])
  );

  const bounds =
    coordinates.length > 1
      ? new LeafletPolygon(
          coordinates.map((item) => new LatLng(item[1], item[0]))
        ).getBounds()
      : undefined;

  return [center, bounds];
}
Example #7
Source File: gameService.ts    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
function sendAddFlight(
  coalition: string,
  country: string,
  location: LatLng,
  airport: number,
  plane: string,
  numberOfPlanes: number
): void {
  sendMessage('add_flight', {
    coalition: coalition,
    country: country,
    location: { lat: location.lat, lon: location.lng },
    airport: airport,
    plane: plane,
    number_of_planes: numberOfPlanes
  });
}
Example #8
Source File: util.ts    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
export function getGoogleEarthUrl(latlng: LatLng) {
  return `https://earth.google.com/web/@${latlng.lat},${latlng.lng},40a,5000d,35y,15h,60t,0r`;
}
Example #9
Source File: appState.ts    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
defaultState: AppState = {
  adminMode: false,
  commanderMode: false,
  showAddFlightForm: false,
  location: new LatLng(0, 0),
  showLoadoutEditor: false,
  showRoleSelectionForm: true,
  showRoleOverview: false,
  showLoadMissionForm: false,
  showSaveAsMissionForm: false
}
Example #10
Source File: PlayerMarker.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
constructor(player: LiveAtlasPlayer, options: PlayerMarkerOptions) {
		super(new LatLng(0, 0), options);
		this._player = player;

		this._PlayerIcon = options.icon = new PlayerIcon(player, {
			imageSize: options.imageSize,
			showHealth: options.showHealth,
			showArmor: options.showArmor,
			showYaw: options.showYaw,
			compact: options.compact,
		});

		Util.setOptions(this, options);
	}
Example #11
Source File: Ruler.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
export function Ruler() {
  const map = useMap();
  const mapCenter = map.getCenter();
  const mapBoundEast = map.getBounds().getEast();
  const mapBoundWest = map.getBounds().getWest();
  const quarter = Math.abs(mapBoundWest - mapBoundEast) / 4.0;
  const [positions, setPositions] = useState([
    new LatLng(mapCenter.lat, mapCenter.lng - quarter),
    new LatLng(mapCenter.lat, mapCenter.lng + quarter)
  ]);

  const handlePositionModified = (index: number, pos: LatLng) => {
    const newPositions = [...positions];
    newPositions[index] = pos;
    setPositions(newPositions);
  };

  return (
    <React.Fragment>
      <EditablePolyline
        positions={positions}
        color="black"
        stroke={true}
        weight={3}
        opacity={1}
        dashArray="1"
        drawMidmarkers={false}
        onPositionModified={handlePositionModified}
      />
      <DistanceMarkers positions={positions} showBearing={true} />
    </React.Fragment>
  );
}
Example #12
Source File: DynmapProjection.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
locationToLatLng(location: Coordinate): LatLng {
		const wtp = this.worldToMap,
			lat = wtp[3] * location.x + wtp[4] * location.y + wtp[5] * location.z,
			lng = wtp[0] * location.x + wtp[1] * location.y + wtp[2] * location.z;

		return new LatLng(
			-((this.tileSize - lat) / (1 << this.nativeZoomLevels)),
			lng / (1 << this.nativeZoomLevels));
	}
Example #13
Source File: CoalitionLayer.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
export function CoalitionLayer(props: CoalitionLayerProps) {
  const { commanderMode } = AppStateContainer.useContainer();
  const { coalition } = props;

  const { lat, lon } = coalition.bullseye;
  const bullseye = new LatLng(lat, lon);

  const { sessionId, sessions } = SessionStateContainer.useContainer();
  const sessionData = sessions[sessionId];
  const sessionCoalition = sessionData ? sessionData.coalition : '';
  const showBullseye = sessionCoalition === coalition.name;

  const onMarkerDragEnd = (event: LeafletEvent) => {
    const latlng = event.target._latlng;
    if (!commanderMode) {
      return;
    }

    gameService.sendSetBullseye(coalition.name, latlng);
  };

  return (
    <CoalitionContext.Provider value={{ sessionCoalition: sessionCoalition, groupCoalition: coalition.name }}>
      {Object.keys(coalition.countries).map(countryKey => (
        <CountryLayer key={countryKey} country={coalition.countries[countryKey]} />
      ))}
      {showBullseye && (
        <BullseyeMarker
          position={bullseye}
          eventHandlers={{
            dragend: onMarkerDragEnd
          }}
          draggable={commanderMode}
        />
      )}
    </CoalitionContext.Provider>
  );
}
Example #14
Source File: DynmapProjection.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
latLngToLocation(latLng: LatLng, y: number): Coordinate {
		const ptw = this.mapToWorld,
			lat = this.tileSize + latLng.lat * (1 << this.nativeZoomLevels),
			lon = latLng.lng * (1 << this.nativeZoomLevels),
			x = ptw[0] * lon + ptw[1] * lat + ptw[2] * y,
			z = ptw[6] * lon + ptw[7] * lat + ptw[8] * y;

		return {x: x, y: y, z: z};
	}
Example #15
Source File: OverviewerProjection.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
locationToLatLng(location: Coordinate): LatLng {
        let lng = 0.5 - (1.0 / Math.pow(2, this.nativeZoomLevels + 1));
        let lat = 0.5;

		if (this.northDirection === this.upperRight) {
            const temp = location.x;
            location.x = -location.z + 15;
            location.z = temp;
        } else if(this.northDirection === this.lowerRight) {
            location.x = -location.x + 15;
            location.z = -location.z + 15;
        } else if(this.northDirection === this.lowerLeft) {
            const temp = location.x;
            location.x = location.z;
            location.z = -temp + 15;
        }

        lng += 12 * location.x * this.perPixel;
        lat -= 6 * location.x * this.perPixel;

        lng += 12 * location.z * this.perPixel;
        lat += 6 * location.z * this.perPixel;

        lng += 12 * this.perPixel;
        lat += 12 * (256 - location.y) * this.perPixel;

        return new LatLng(-lat * this.tileSize, lng * this.tileSize);
	}
Example #16
Source File: OverviewerProjection.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
latLngToLocation(latLng: LatLng, y: number): Coordinate {
        const lat = (-latLng.lat / this.tileSize) - 0.5;
        const lng = (latLng.lng / this.tileSize) - (0.5 - (1.0 / Math.pow(2, this.nativeZoomLevels + 1)));

        const x = Math.floor((lng - 2 * lat) / (24 * this.perPixel)) + (256 - y),
			z = Math.floor((lng + 2 * lat) / (24 * this.perPixel)) - (256 - y);

		if (this.northDirection == this.upperRight) {
			return {x: z, y, z: -x + 15}
		} else if (this.northDirection == this.lowerRight) {
			return {x: -x + 15, y, z: -y + 15}
		} else if (this.northDirection == this.lowerLeft) {
			return {x: -z + 15, y, z: x}
		}

        return {x, y, z};
	}
Example #17
Source File: RegionLabelLayer.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
_RegionLabelLayer: FunctionComponent<RegionLabelLayerProps> = ({ displayed, zoomLevel }) => {
  const classes = useStyles();

  const map = useMap();
  const layerReference = useRef<GeoJSONLeaflet | null>(null);

  useEffect(() => {
    if (layerReference.current != null) {
      if (displayed) {
        layerReference.current.addTo(map);
      } else {
        layerReference.current.removeFrom(map);
      }
    }
  }, [map, displayed]);

  const pointToLayer = (featureData: Feature<Point, any>, latLng: LatLng) => {
    const html = renderToString(<RegionLabel featureData={featureData} zoomLevel={zoomLevel} />);

    return LeafletMarker([latLng.lng, latLng.lat], {
      interactive: false, // Allow clicks to pass through.
      icon: LeafletDivIcon({
        html,
        className: classes.regionLabelMarker,
      }),
      zIndexOffset: -900,
    });
  };

  return (
    <GeoJSON
      ref={layerReference}
      key={zoomLevel}
      pointToLayer={pointToLayer}
      data={RegionLabelData as GeoJsonObject}
    />
  );
}
Example #18
Source File: LiveAtlasMapDefinition.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
locationToLatLng(location: Coordinate): LatLng {
		return this.projection ? this.projection.locationToLatLng(location)
			: new LatLng(-location.z * this.scale, location.x * this.scale);
	}
Example #19
Source File: map.component.ts    From dayz-server-manager with MIT License 5 votes vote down vote up
private unproject(coords: PointExpression): LatLng {
        return this.map!.unproject(coords, this.mapScale!);
    }
Example #20
Source File: map.component.ts    From dayz-server-manager with MIT License 5 votes vote down vote up
private project(coords: LatLng): Point {
        return this.map!.project(coords, this.mapScale!);
    }
Example #21
Source File: index.tsx    From aqualink-app with MIT License 5 votes vote down vote up
INITIAL_CENTER = new LatLng(0, 121.3)
Example #22
Source File: gameService.ts    From project-tauntaun with GNU Lesser General Public License v3.0 5 votes vote down vote up
function sendSetBullseye(coalition: string, bullseye: LatLng) {
  sendMessage('set_bullseye', {
    coalition: coalition,
    bullseye: { lat: bullseye.lat, lon: bullseye.lng }
  });
}
Example #23
Source File: gameService.ts    From project-tauntaun with GNU Lesser General Public License v3.0 5 votes vote down vote up
function sendAddJTAC(coalition: string, country: string, location: LatLng): void {
  sendMessage('add_jtac', {
    coalition: coalition,
    country: country,
    location: { lat: location.lat, lon: location.lng }
  });
}
Example #24
Source File: LiveAtlasMapDefinition.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
latLngToLocation(latLng: LatLng, y: number): Coordinate {
		return this.projection ? this.projection.latLngToLocation(latLng, y)
			: {x: latLng.lng / this.scale, y: y, z: -latLng.lat / this.scale};
	}
Example #25
Source File: CampaignMap.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 5 votes vote down vote up
export function CampaignMap(props: CampaignMapProps) {
  const { mission } = MissionStateContainer.useContainer();
  const { mapType, showLegend, showRuler } = MapStateContainer.useContainer();

  const { sessionId, sessions } = SessionStateContainer.useContainer();
  const sessionData = sessions[sessionId];
  const sessionCoalition = sessionData ? sessionData.coalition : '';

  const [position, setPosition] = useState(null as ClickPosition | null);
  const center = new LatLng(props.lat, props.lng);

  const onContextMenuClick = (event: any) => {
    event.originalEvent.preventDefault();
    setPosition({
      xy: {
        x: event.originalEvent.clientX,
        y: event.originalEvent.clientY
      } as PointXY,
      latlon: event.latlng
    } as ClickPosition);
  };

  // Need to add a second layer with labels for these three basemaps.
  const layersNeedingLabels = ['Imagery', 'Gray', 'DarkGray'];
  const showLabels = layersNeedingLabels.includes(mapType);
  const labelLayerName = (mapType + 'Labels') as Basemaps;

  return (
    <div data-testid="campaign-map">
      <LegendContext.Provider value={{ legends: [] }}>
        <MapContainer
          center={center}
          zoom={props.zoom}
          preferCanvas={true}
          doubleClickZoom={false}
          inertia={false}
          zoomControl={false}
        >
          <BasemapLayer key={mapType} name={mapType} />
          {showLabels && <BasemapLayer key={labelLayerName} name={labelLayerName} />}
          <CampaignMapEventHandler
            eventHandlers={{
              contextmenu: onContextMenuClick
            }}
          />
          {sessionCoalition && (
            <React.Fragment>
              <AirportLayer airports={mission.terrain.airports} />
              {Object.keys(mission.coalition).map(key => (
                <CoalitionLayer key={key} coalition={mission.coalition[key]} />
              ))}
            </React.Fragment>
          )}
          {position && <MapContextMenu position={position} />}
          {showRuler && <Ruler />}
        </MapContainer>
        {showLegend && <Legend />}
      </LegendContext.Provider>
    </div>
  );
}
Example #26
Source File: appState.ts    From project-tauntaun with GNU Lesser General Public License v3.0 5 votes vote down vote up
function useAppState(initialState = defaultState) {
  const [state, setState] = useState(initialState);

  const setLocation = (location: LatLng) => {
    setState(state => ({
      ...state,
      location: location
    }));
  };

  const setAdminMode = (adminMode: boolean) => {
    setState(state => ({
      ...state,
      adminMode: adminMode
    }));
  };

  const setShowLoadoutEditor = (visible: boolean) => {
    setState(state => ({
      ...state,
      showLoadoutEditor: visible
    }));
  };

  const setShowAddFlightForm = (visible: boolean) => {
    setState(state => ({
      ...state,
      showAddFlightForm: visible
    }));
  };

  const setShowRoleSelectionForm = (visible: boolean) => {
    setState(state => ({
      ...state,
      showRoleSelectionForm: visible
    }));
  };

  const setCommanderMode = (commanderMode: boolean) => {
    setState(state => ({
      ...state,
      commanderMode: commanderMode
    }));
  };

  const setShowRoleOverview = (showRoleOverview: boolean) => {
    setState(state => ({
      ...state,
      showRoleOverview: showRoleOverview
    }));
  };

  const setShowLoadMissionForm = (showLoadMissionForm: boolean) => {
    setState(state => ({
      ...state,
      showLoadMissionForm: showLoadMissionForm
    }));
  };

  const setShowSaveAsMissionForm = (showSaveAsMissionForm: boolean) => {
    setState(state => ({
      ...state,
      showSaveAsMissionForm: showSaveAsMissionForm
    }));
  };

  return {
    ...state,
    setAdminMode,
    setShowLoadoutEditor,
    setLocation,
    setShowAddFlightForm,
    setShowRoleSelectionForm,
    setShowRoleOverview,
    setCommanderMode,
    setShowLoadMissionForm,
    setShowSaveAsMissionForm
  };
}
Example #27
Source File: BullseyeMarker.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 5 votes vote down vote up
export function BullseyeMarker(props: MarkerProps) {
  const { draggable } = props;
  const position = props.position as LatLng;

  const memorizedItem = useMemo(() => <BullseyeMarkerNonMemo {...props} />, [position.lat, position.lng, draggable]);

  return memorizedItem;
}
Example #28
Source File: DistanceMarkers.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 5 votes vote down vote up
export function DistanceMarkers(props: DistanceMarkersProps) {
  const { positions, showBearing: showBearingProp, showDistance: showDistanceProp } = props;

  const showBearing = showBearingProp ? showBearingProp : false;
  const showDistance = showDistanceProp ? showDistanceProp : true;

  const midPoint = (a: LatLng, b: LatLng) => {
    const lat = a.lat + (b.lat - a.lat) * 0.5;
    const lng = a.lng + (b.lng - a.lng) * 0.5;
    return new LatLng(lat, lng);
  };

  const distances = positions.reduce(
    (p, c, i, array) => (i < array.length - 1 ? [...p, c.distanceTo(array[i + 1]) * c_MeterToNm] : [...p]),
    [] as number[]
  );

  const bearings = positions.reduce(
    (p, c, i, array) => (i < array.length - 1 ? [...p, calculateBearing(c, array[i + 1])] : [...p]),
    [] as number[]
  );

  const distanceTextPositions = positions.reduce(
    (p, c, i, array) => (i < array.length - 1 ? [...p, midPoint(array[i + 1], c)] : [...p]),
    [] as LatLng[]
  );

  return (
    <React.Fragment>
      {distanceTextPositions.map((p, i) => {
        const bearing = showBearing ? bearings[i].toFixed(0) + '\xb0 ' : '';
        const distance = showDistance ? distances[i].toFixed(1) : '';
        const text = `${bearing}${distance}`;
        return (
          <TextMarker
            key={`distance_text${i}`}
            text={text}
            position={p}
            color={'white'}
            backgroundColor={'black'}
            size={11}
          />
        );
      })}
    </React.Fragment>
  );
}
Example #29
Source File: EditablePolyline.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 5 votes vote down vote up
export function EditablePolyline(props: EditablePolylineProps) {
  const { drawMarkers, positions } = props;
  const latLngArray = JSON.stringify(positions as LatLng[]);

  const memorizedItem = useMemo(() => <EditablePolylineNonMemo {...props} />, [drawMarkers, latLngArray]);

  return memorizedItem;
}