Coder Social home page Coder Social logo

beyonk-group / svelte-mapbox Goto Github PK

View Code? Open in Web Editor NEW
334.0 9.0 61.0 1.16 MB

MapBox Map and Autocomplete components for Svelte (or Vanilla JS)

License: MIT License

JavaScript 17.11% Svelte 52.90% HTML 2.18% CSS 27.81%
mapbox svelte google-maps maps autocomplete geocoding geocode location mapping

svelte-mapbox's Introduction





Svelte MapBox

js-standard-style svelte-v3 publish

Maps and Geocoding (Autocomplete) MapBox components in Vanilla JS (or Svelte)

  • SvelteKit Ready

  • SSR Ready

  • Lightweight

  • No clientside dependencies (Map)

  • Allow creation of custom Svelte components on the map

  • Note that the GeoCoder has a clientside dependency, since it adds about 0.5mb to the bundle size, and significant time to the build time if bundled.

Installing

npm install --save-dev @beyonk/svelte-mapbox

Basic Usage (Map)

The container component is the map, and there are a variety of components which go on the map.

<Map
  accessToken="<your api key>" // add your api key here
  bind:this={mapComponent} // Get reference to your map component to use methods
  on:recentre={e => console.log(e.detail.center.lat, e.detail.center.lng) } // recentre events
  options={{ scrollZoom: false }} // // add arbitrary options to the map from the mapbox api
>
  <Earthquakes /> // Any custom component you create or want here - see marker example
  <Marker lat={someLat} lng={someLng} color="rgb(255,255,255)" label="some marker label" popupClassName="class-name" /> // built in Marker component
  <NavigationControl />
  <GeolocateControl options={{ some: 'control-option' }} on:eventname={eventHandler} />
  <ScaleControl />
</Map>

<script>
  import { Map, Geocoder, Marker, controls } from '@beyonk/svelte-mapbox'
	import Earthquakes from './Earthquakes.svelte' // custom component
  
  const { GeolocateControl, NavigationControl, ScaleControl } = controls

  // Usage of methods like setCenter and flyto
  mapComponent.setCenter([lng,lat],zoom) // zoom is optional
  mapComponent.flyTo({center:[lng,lat]}) // documentation (https://docs.mapbox.com/mapbox-gl-js/example/flyto)

  // Define this to handle `eventname` events - see [GeoLocate Events](https://docs.mapbox.com/mapbox-gl-js/api/markers/#geolocatecontrol-events)
  function eventHandler (e) {
    const data = e.detail
    // do something with `data`, it's the result returned from the mapbox event
  }
</script>

<style>
    :global(.mapboxgl-map) {
        height: 200px;
        // sometimes mapbox objects don't render as expected; troubleshoot by changing the height/width to px
    }
</style>

Markers

By default, markers are typical map pins to which you can pass a color property.

<Marker color={brandColour} />

You may also create a custom pin with the default slot.

<Marker
lat={waypoint.geo.lat}
lng={waypoint.geo.lng}
> 
  <a href={waypoint.slug}>
    <div class='myMarker {($mapData.activeMarker == waypoint.id) ? 'active' : ''}' 
    style="
    color:{mainPoint.color};
    background-image: url('{(waypoint.images != undefined) ? waypoint.images[0].thumb.url : ''}');
    ">
    </div>
  </a>
</Marker>

Marker Popups

By default a popup is revealed when you click a pin. It is populated with text provided in the label property.

<Marker label={markerText} />

To indicate interactivity, you may target the marker with some custom CSS:

<style>
    :global(.mapboxgl-marker){
      cursor: pointer;
    }   
</style>

Optionally, disable the popup with the popup={false} property:

<Marker popup={false} />

You may alternatively pass a custom DOM element to the marker to use as a popup.

<Marker lat={pin.coordinates.latitude} lng={pin.coordinates.longitude}>
    <div class="content" slot="popup">
      <h3>{pin.name}</h3>
        <Markdown source={pin.description} />
      </div>
      <img src="{pin.images.length > 0 ? pin.images[0].url : ""}" alt="{pin.name}"/>
    </div> 
</Marker>

Reactive Properties

The map has reactive properties for center and zoom. This means that if you set these properties, or modify them whilst the map is displayed, the map will react accordingly.

This also means that if you bind these properties to a variable, that variable will automatically be updated with the current center and zoom of the map if the user moves or zooms the map.

This is often easier than waiting for events such as recentre or zoom to be fired, to update markers and similar:

<Map accessToken="<your api key>" bind:center bind:zoom>
  <Marker bind:lat bind:lng />
</Map>

<script>
  let center
  let zoom

  $: lng = center[0]
  $: lat = center[1]
</script>

Methods

The map has a variety of methods which delegate to a queue. The reason for this is that MapBox is quite a heavy library, and rendering a map is a pretty heavy operation. It's hard to guarantee when everything is ready in your browser, and when you can start doing things with it.

In case you want raw map access to interact directly with the map, you can call getMap on the map and interact with it that way. However we don't recommend it, as you have no guarantees that the map is ready in your browser when you call it this way.

Basic Usage (Geocoder)

The Geocoder is an autocompleting place lookup, which returns a lat and lng for a place.

<Geocoder accessToken="<your api key>" on:result={somePlaceChangeFunction} />

<script>
  import { Geocoder } from '@beyonk/svelte-mapbox'
</script>

The geocoder has five events you can subscribe to: on:loading, on:result, on:results, on:clear, and on:error which are documented here

The most important event is on:result which is fired when a user selects an autocomplete result.

There is a sixth event specific to this library, which is on:ready, which is fired when the component is ready for use. You can likely ignore it.

Custom CSS

You can add additional css to override mapbox provided CSS by passing the customStylesheetUrl property to either the Map or Geocoder components.

Demo

To see the earthquakes demo:

Make sure you copy the .env file to .env.local and then populate it with your mapbox key.

npm run dev

svelte-mapbox's People

Contributors

ahpercival avatar amerlander avatar andreashald avatar antony avatar brittharr avatar craigchamberlain avatar cucharadepalo avatar dependabot[bot] avatar eur2 avatar jamesatjaminit avatar jbixon13 avatar kidandcat avatar lucianvoju avatar markfirmware avatar nfk avatar sdl60660 avatar singingwolfboy avatar the-yadu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

svelte-mapbox's Issues

Improve Basic Usage (Map) example on readme

The basic example is uncompleted and does not expose the event ready, which is a requirement to use the mapComponent.

Maybe a working example in REPL can help the user (I dont know if we can do that)

Importing component results in: TypeError: Cannot read property 'replace' of undefined

Hey there,

I'm trying to give your component a whirl...

When I try to start my app, I'm getting this error when I import your component.

I'm new to Svelte, Snowpack and rollup, so probably something I'm doing wrong.

Any clues?

Thanks a lot!

Snowpack

  Server starting…

  mount:web_modules.......[READY] mount $WEB_MODULES --to /web_modules
  mount:public............[READY] mount public --to /
  mount:src...............[READY] mount src --to /_dist_
  build:js,jsx,ts,tsx.....[READY] (default) esbuild
  build:svelte............[READY] (plugin) @snowpack/plugin-svelte

▼ Console

  [log] ! updating dependencies...
  [error] 
  TypeError: Cannot read property 'replace' of undefined
      at Object.onwarn (/home/xyz/dev/maptest/node_modules/snowpack/dist-node/index.js:1924:37)
      at Object.config.onwarn.warning [as onwarn] (/home/xyz/dev/maptest/node_modules/rollup/dist/shared/rollup.js:18930:20)
      at Object.warn (/home/xyz/dev/maptest/node_modules/rollup/dist/shared/rollup.js:17974:25)
      at Object.resolveId (/home/xyz/dev/maptest/node_modules/snowpack/dist-node/index.js:939:14)
      at Promise.resolve.then (/home/xyz/dev/maptest/node_modules/rollup/dist/shared/rollup.js:18134:25)

Is cooperativeGestures parameter supported?

I'd like to use this option for better UX on mobile.

So far I've tried adding it to the Map component as a prop, to the mapComponent object, and as an option, but having no luck.

<Map
  accessToken={PUBLIC_MAPBOX_API_TOKEN}
  style="mapbox://styles/mapbox/outdoors-v11"
  bind:this={mapComponent}
  on:ready={onReady}
  center={[event.location.lng, event.location.lat]}
  zoom="4"
  cooperativeGestures={true}
// or
  options={{ cooperativeGestures: true }}
>

or mapComponent.cooperativeGesture = true;
or mapComponent.options = {cooperativeGesture = true};

Thought I'd check if it's supported or something I'm doing wrong. (most likely the latter, i'm a Svelte noob!)

Access to Markers via code

I am currently adding markers to the map like this: (I have custom Marker Icons and popup code, this example is simplified).

<Map> {#if markers} {#each markers as m} <Marker lng={m.longitude} lat={m.latitude} label={m.name} /> {/each} {/if} </Map>

Is there a way to build these markers in code and add them to the map? I need the ability to add and remove markers based on the result of an API call.

Currently, when the API returns 0 markers I set the variable markers to null and receive this error: TypeError: Cannot read properties of null (reading 'removeChild')... I can add more detail if you need it.

Thank you.

Multiple maps on same page

Whatever you do, when you use more than one Map element on same page (DOM), then page wont load:

Cannot set properties of undefined (setting 'accessToken')

Get access to map object

How to get access to map object to use mapbox additional funcitionality such as flyto?

Also how to import Marker component?

ready event on <Map> not firing anymore on 8.1.1

I'm on Sapper 0.29.2 where I've worked on a map over the last few days using the following code where on:ready fired as expected:

              <Map
                accessToken=ROLLUP_MAPBOX_EDM_DEFAULT_PUBLIC_ACCESS_TOKEN
                bind:this={ mapComponent }
                bind:zoom
                on:click={ toggleStyle }
                on:ready={ () => console.log('inline ready event...') }
                on:dragend={ colorizeBuildings }
                on:dragend={ showUrbanAreas }
                on:zoomend={ colorizeBuildings }
                on:zoomend={ showUrbanAreas }
                on:zoomstart={ toggleStyle }
                options={{ attributionControl: false, antialias: true }}
                style = { $userStore.userCurrenMapBoxTheme }
              >
  1. However, after upgrading from 7.7.1 to 8.1.1 on:ready doesn't fire anymore i.e in the above snippet console.log() never prints to the console? 🤔
  2. What I also noticed just now is that bind:zoom stopped working i.e. using { zoom } somewhere on the page to show the user his current zoom level worked in 7.7.1 but stopped working after upgrading to version 8.1.1

@antony does on:ready work for you at this point i.e. using 8.1.1? I just went back to 7.7.1 and all works again, no change to my source, just downgrading svelte-mapbox 🤷‍♂️

Cannot find module

Error: Cannot find module 'C:\...\node_modules\@beyonk\svelte-mapbox\index.mjs'. Please verify that the package.json has a valid "main" entry

I am attempting to use this component in Sapper, but when I try to import it I get the above error. Let me know if you need additional information.

Any change Marker lat lng does not reflect in mapbox

Marker lat lng updates as expected once when it is rendered for the first time.
Marker does not update if its lat and lng props are changed or modified.

Is there a special way to do it or its not handled?

I can raise PR if required.

Custom markers

I try to add a Marker with custom element.

The element property seems not to be usable:
<Marker element={myImage} lat=0 lng=0 />

Marker.svelte:51 <Marker> was created with unknown prop 'element'

Is this a missing feature, or do I something wrong?

doesnt work with SvelteKit

Hi, I tried using your package with the example code but nothing shows up on the page.

My code is this:

<script>
    import { Map, Geocoder, Marker, controls } from "@beyonk/svelte-mapbox";

    const { GeolocateControl, NavigationControl, ScaleControl } = controls;

    let mapComponent;
    let lng = 69;
    let lat = 69;
    let zoom = 19;
    // Usage of methods like setCenter and flyto
    function onReady() {
        mapComponent.setCenter([lng, lat], zoom); // zoom is optional
        mapComponent.flyTo({ center: [lng, lat] }); // documentation (https://docs.mapbox.com/mapbox-gl-js/example/flyto)
    }

    // Define this to handle `eventname` events - see [GeoLocate Events](https://docs.mapbox.com/mapbox-gl-js/api/markers/#geolocatecontrol-events)
    function eventHandler(e) {
        const data = e.detail;
        // do something with `data`, it's the result returned from the mapbox event
    }
</script>

<Map
    accessToken="token"
    bind:this={mapComponent}
    on:recentre={(e) => console.log(e.detail.center.lat, e.detail.center.lng)}
    on:ready={onReady}
    options={{ scrollZoom: false }}
/>

Svelte Kit can't find @beyonk/svelte-mapbox

TBH I have no clue what is the source of the problem && it seems a bit awkward, but let me ask anyway...

Initially been struggling with #44 but after tweaking optimizeDeps as adviced it went away. So far so good.

But right now it seems an app doesn't see @beyonk/svelte-mapbox at all... Installed it as a dev dependency using both yarn and npm, removed node_modules & locks, reinstalled, upgraded all deps, did it once again - same thing over and over again.

Constantly getting Cannot find module '@beyonk/svelte-mapbox'.

I am really puzzled... Any ideas?

How to get GeoCoder selected result?

Hi.

I'm using the map and geocoder componentes but I cant figure out how to get the clicked lat and lng from the clicked result. I fire the event on:result={somePlaceChangeFunction} but how can pass the coordinate information to that function or bind the values to varaibles?

Thank you!

Could not find a declaration file for module '@beyonk/svelte-mapbox'.

When using SvelteKit, then this eslinting error is shown.

Could not find a declaration file for module '@beyonk/svelte-mapbox'. '/node_modules/@beyonk/svelte-mapbox/src/lib/components.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/beyonk__svelte-mapbox` if it exists or add a new declaration (.d.ts) file containing `declare module '@beyonk/svelte-mapbox';`ts(7016)

npm i --save-dev @types/beyonk__svelte-mapbox

does not help as there are no types defined in
https://registry.npmjs.org/@types%2fbeyonk__svelte-mapbox

Cannot find module

Error: Cannot find module '/front/node_modules/@beyonk/svelte-mapbox/index.mjs'. Please verify that the package.json has a valid "main" entry

at tryPackage (internal/modules/cjs/loader.js:322:19)
    at Function.Module._findPath (internal/modules/cjs/loader.js:683:18)
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:953:27)
    at Function.Module._load (internal/modules/cjs/loader.js:842:27)
    at Module.require (internal/modules/cjs/loader.js:1026:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/front/__sapper__/dev/server/server.js:24:20)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32) {
  code: 'MODULE_NOT_FOUND',
  path: '/front/node_modules/@beyonk/svelte-mapbox/package.json',
  requestPath: '@beyonk/svelte-mapbox'

How do you search for places using the geocoder ?

I'm using your amazing sveltekit package on my side project, however when i search for places using the geocoder it doesnt retreive them, i just get countries and cities. when using a map on mapbox's site with all the filters turned off, it finds the place i'm searching for. should i be passing some options to the geocoder so that it doesn't do any filtering of what i'm typing ? if so, whats the best way to do this with the way you've implemented it ? thx!

eg. if you goto the link below and remove the filters you'll see that searching for 'soho house berlin' will return a result, however with the filters on, it doesn't.

https://docs.mapbox.com/playground/geocoding/

map.remove is not a function

Atleast in svelte it appears that when navigating to a page that begins loading the map component, but navigating away before it has initialized will cause the component to fail because map.remove is not a function

event

on:click can not be used at Map component

Setting $session in Sveltekit breaks the map

If I have a page displaying the map and add the following code it breaks.

import { session } from '$app/stores';
import { browser } from '$app/env';

if (browser) {
  // try to set the $session to anything
  $session = 'asdf'
}

The error I get in the console is:

Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'window.mapboxgl.accessToken = options.accessToken')
init — map-action.js:31
(anonymous function) — map-action.js:19
load — asset-loader.js:7
action — map-action.js:18
mount — Map.svelte:15
(anonymous function) — svelte-hooks.js:197
mount_component — index.mjs:1727
mount — index.svelte:28
(anonymous function) — svelte-hooks.js:197
mount_component — index.mjs:1727
update — root.svelte:38
update — root.svelte:37
update_slot_base — index.mjs:98
update — layout.svelte:40
update — index.mjs:1057
flush — index.mjs:1025
promiseReactionJob
B — util.js:516

Annoying TS error when using Map

So I finally have a simple map going (yay!) -- but I am using SvelteKit -- and it has TypeScript on by default (or at least this project does) -- and besides VS Code complainign about a bunch of things in Map itself it does like:

  • Property 'mapboxgl' does not exist on type 'Window & typeof globalThis'.[76,12]
  • Property 'mapboxgl' does not exist on type 'Window & typeof globalThis'.[77,21]
  • Type 'boolean' is not assignable to type 'string'. [134,39]
  • Property 'mapboxgl' does not exist on type 'Window & typeof globalThis'. [139, 22]

It is also complaining in my Svelte component about the usage of the {center} arg. I have, as per the example:
let center = { lat: 36.0999, lng: -80.2442 };

And use it thusly:

<div class="map-wrap">
	<Map
		bind:this={mapComponent}
		bind:zoom
		accessToken={mapboxAPI}
		on:recentre={(e) => console.log(e.detail)}
		{center}
	>
		<Marker lat={center.lat} lng={center.lng} />
	</Map>
</div>

The error / warnring message I am getting is:

Type '{ lat: number; lng: number; }' is not assignable to type 'number[]'.

Just wondering if anyone has an idea about this -- the app actually works and renders a map -- so -- it's obviously not fatal but .. just trying to learn TS (I think)..

TIA!

/Steve

Create new release

Could you create a new release with the issue i submitted a couple of weeks ago?

How can I update the source and layer data on the rendered map?

Is there any way to programatically update the source and layer data on the rendered map?

For example, on map initialization, including code like this:

    map.addSource("selectedLocation", {
        type: "geojson",
        data: selectedLocationData
    });
    map.addLayer({
        id: "selectedLocationHighlight",
        type: "fill",
        source: "selectedLocation",
        paint: {
            "fill-color": "blue"
        }
    });

And when the location changes (via Geocoder), I would fetch a geojson for that location and update the map's source and layers liks this:

var selectedLocation = mapComponent.getSource('selectedLocation')
selectedLocation.setData(newLocationGeojson)

My code is similar to the demos in the readme, and I've tried a few ways -- for example, mapComponent.getSource('selectedLocation')

But everything is returning errors thus far.

Any help/advice would be much appreciated!

Demo not working

Hi there,

Just wanted to point out that the demo isn't displaying any maps on firefox, brave, chrome.

Would love to try this!

getContext for custom svelte map component

I am currently experimenting with using svelte-mapbox in my project.

As part of this, I have built a custom 'mapLine.svelte' component.

I am trying to getContext in the following way:

import { contextKey } from '@beyonk/svelte-mapbox/src/lib/mapbox' const { getMap } = getContext(contextKey);

This is not working as expected though. For this to work, I have to set contextKey to a "string" for it to successfully getContext in svelte.in the mapbox.js file I am importing.

mapbox.js file updated from:
const contextKey = {} export { contextKey }

to
const contextKey = "contextKey" export { contextKey }

Keen to understand the correct way to do this.

The other thing I tried was to set the contextKey in my project, and pass this in as a parameter to @beyonk Map.svelte component. this also worked..

What is the recommended way to achieve custom components with this library?

Popup Options

Atm, the following options are listed by name.

 const popupEl = new mapbox.Popup({
  offset: popupOffset,
  className: popupClassName
})

There are a good number of other options in the API in the Docs

My problem here is that naming all of them in the marker is going to get a bit excessive. If I were to merge popupOffset & popupClassName into and popupOptions object this would be a breaking change. :(

What are the implications of spreading an object

const popupEl = new mapbox.Popup({
  offset: popupOffset,
  className: popupClassName,
  ...popupOptions
})

Would something like this be better

namedParams = { offset: popupOffset,  className: popupClassName }
const popupEl = new mapbox.Popup(Object.assign(namedParams, popupOptions))

Error when using with Svelte Kit

Hello,
I have this error when using with Svelte Kit:
'/node_modules/fastq/queue.js?v=607b44ec' does not provide an export named 'default'

Thanks

HTML(Links) in labels

Hello,

Thanks for contributing this package(and your awesome google analytics package!).

Is there a built-in way to use html/links in a label?

Something like:

<Map ...>
  <Marker lat={center.lat} lng={center.lng} label="Coordinate: {center.lat}, {center.lng} <br /><a href='https://detail.page' target='_blank'>See more</a>">
  </Marker>
</Map>

It looks like the label function uses setText.

There is also a setHTML function an the official mapbox demo, but I could not find an analogous way in your wrapper.

Is there a simple way to do this with your package? Or should you go the DOM route?

Thanks in advance for any advice on best way to implement.

map height

Thanks for this library!

I understand the map can be displayed by setting a fixed height in pixels, however this is inconvenient... is there no way to have it take the full height of the parent container?

can this be fixed?
what seems to be causing this behaviour?

SvelteKit build fails due to peer dependency issues with Svelte v4

With the new Svelte 4 release, trying to build my SvelteKit project fails due to the peer svelte@"^3.0.0" dependency in Svelte-mapbox.

Just messing with it in dev, I don't have any issues using Svelte 4 with the current version of Svelte-mapbox.

I don't know what testing you would want to do before bumping that number up to include Svelte 4, or I would just submit a pull request to fix it.

Thank you for the great package, I use it in multiple sites with great success.

The full error on Cloudflare Pages:

12:30:43.619 | npm ERR! Found: [email protected]
12:30:43.619 | npm ERR! node_modules/svelte
12:30:43.619 | npm ERR!   dev svelte@"^4.0.0" from the root project
12:30:43.619 | npm ERR!
12:30:43.619 | npm ERR! Could not resolve dependency:
12:30:43.620 | npm ERR! peer svelte@"^3.0.0" from @beyonk/[email protected]
12:30:43.620 | npm ERR! node_modules/@beyonk/svelte-mapbox
12:30:43.620 | npm ERR!   dev @beyonk/svelte-mapbox@"^9.1.0" from the root project
12:30:43.620 | npm ERR!
12:30:43.620 | npm ERR! Fix the upstream dependency conflict, or retry
12:30:43.620 | npm ERR! this command with --force, or --legacy-peer-deps

adding --force to the build command does not fix the problem.

Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'accessToken')

I have an error that triggers every page reload. I have the most simplified version of the software set up

<script>
	import { PUBLIC_MAPBOX_TOKEN } from '$env/static/public';
	import { Map, Geocoder, Marker, controls } from '@beyonk/svelte-mapbox';

	let zoom = 11.15;
</script>

<div class="map-wrap">
	<Map accessToken={PUBLIC_MAPBOX_TOKEN} bind:zoom />
</div>

<style>
	.map-wrap {
		width: 100%;
		height: 600px;
	}
</style>

When I comment out the component it works, as in, the page loads.

ncaught (in promise) TypeError: Cannot set properties of undefined (setting 'accessToken')
    at init2 (map-action.js:31:19)
    at map-action.js:19:14
    at load (asset-loader.js:7:9)
    at action (map-action.js:18:3)
    at Object.mount [as m] (Map.svelte:16:6)
    at mount_component (index.mjs:2097:26)
    at mount (+page.svelte:11:6)
    at targetCmp.$$.fragment.m (svelte-hooks.js?v=1008514d:291:24)
    at mount_component (index.mjs:2097:26)
    at Object.update [as p] (root.svelte:48:45)
this is the browser error when the page loads
    proxy.js?v=1008514d:15 [HMR][Svelte] Unrecoverable HMR error in <Root>: next update will trigger a full reload
logError @ proxy.js?v=1008514d:15
Proxy<Root> @ proxy.js?v=1008514d:380
initialize @ client.js?v=1008514d:284
_hydrate @ client.js?v=1008514d:1793
await in _hydrate (async)
start @ start.js:22
(anonymous) @ new:7034
Promise.then (async)
(anonymous) @ new:7033
map-action.js:31 Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'accessToken')
    at init2 (map-action.js:31:19)
    at map-action.js:19:14
    at load (asset-loader.js:7:9)
    at action (map-action.js:18:3)
    at Object.mount [as m] (Map.svelte:16:6)
    at mount_component (index.mjs:2097:26)
    at mount (+page.svelte:11:6)
    at targetCmp.$$.fragment.m (svelte-hooks.js?v=1008514d:291:24)
    at mount_component (index.mjs:2097:26)
    at Object.mount [as m] (root.svelte:48:86)
here is the error when i refresh the page and the map works. Does anyone have a clue what might be going on here?

Event dispatching from <Marker /> elements

Hi,

I can't seem to add eventhandlers for Marker components whereas for the Map component it works just fine. Am I missing something? Simplified pseudocode:

<script>
...
let showPanel;
const onMapReady = () => {
    // This DOES get called
};
const onMarkerReady = () => {
    // But this NOT
};
const handleClick = () => {
    showPanel = !showPanel; // Does NOT get called
};
<script>

<section>
{#await getMarkerData()}
Loading...
{:then markers}
<Map
accessToken="..."
style="mapbox://styles/mapbox/satellite-v9"
zoom="6"
{center}
bind:this={mapComponent}
on:ready={onMapReady}>
{#if markers}
  {#each markers as marker}
     <Marker lat={marker.lat} lng={marker.lng} label={marker.label} on:ready={onMarkerReady} on:click={handleClick} />
  {/each}
{/if}
</Map>
{/await}
</section>

Source and Layer components

Hello, are there any plans on adding Source and Layer reactive components? Something like react-map-gl has.

Resize events

If your working on a responsive design, flipping the device for example might cause the map to change shape or size. This only seems to happen on refresh.

Issue with multiple maps on a page?

When i have 2 components that are Map's on a page I get the following error not sure how to fix this.

map-action.js:31
Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'accessToken')
at init (map-action.js:31:31)
at map-action.js:19:14
at load (asset-loader.js:7:9)
at action (map-action.js:18:3)
at mount (Map.svelte? [sm]:15:6)
at Object.targetCmp.$$.fragment.m (svelte-hooks.js:216:24)
at mount_component (index.mjs:1798:26)
at mount (MapBox.svelte:36:12)
at Object.targetCmp.$$.fragment.m (svelte-hooks.js:216:24)
at mount_component (index.mjs:1798:26)

Marker.color types are invalid

When creating a Marker, the typescript reports the color attribute to be a number. However, it should actually support strings as per mapbox documentation.

From what I gather, you aren't creating typescript types yourself, so it's likely as a result of the randomColour() function. Maybe this function could be changed to produce a random hex code (therefore returning a string) and then the types would be correct?

Example:

<Marker lng={long} {lat} label={name} color="#414288" />

Error:

Type 'string' is not assignable to type 'number'.ts(2322)

Can someone add a license for the repository?

Thank you guys so much for providing this resource.

Can one of the maintainers/project owners add a license? I would like to explore building with this, but I don't want to override any permissions in doing so.

Should be able to pass options through to map methods as you'd be able to do with a native mapbox implementation (e.g. fitBounds)

I noticed while using the fitBounds method, that it didn't support passing through the options available to that mapbox function, such as turning off animation (which is what I was trying to do).

It seems to me that this should be as straightforward as adding an optional parameter on your Map.svelte component's methods, which is what I did locally to make it work. For example:

export function fitBounds (bbox) {
  queue.send('fitBounds', [ bbox ])
}

Just becomes...

export function fitBounds (bbox, options={}) {
    queue.send('fitBounds', [ bbox, options ])
}

I'd be happy to submit a pull request to this effect, but I'm not sure if there was a reason things were implemented this way, without options.

TypeError: Cannot use 'in' operator to search for 'offset' in undefined

If I set "popup = true," my markers do not render and I get: "TypeError: Cannot use 'in' operator to search for 'offset' in undefined." However, if I set "popup = false," my markers render, but without a popup.

Oddly, the popups work in a development environment, but they fail in a production environment. I'm using Heroku and have set "NPM_CONFIG_PRODUCTION = false"; is it possible that this is causing the error? I've been trying to fix this for two and a half months. Please advise.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.