Giter Club home page Giter Club logo

eon-map's Introduction

Please note that this project is no longer actively maintained or accepting Pull Requests. The EON library remains available on npm, bower, or through hotlink.


EON Maps

Real-time location tracking powered by PubNub and MapBox or Google Maps.

Examples

Installing

Hotlink

<script type="text/javascript" src="https://pubnub.github.io/eon/v/eon/1.0.0/eon.js"></script>
<link type="text/css" rel="stylesheet" href="https://pubnub.github.io/eon/v/eon/1.0.0/eon.css"/>

Bower

bower install eon-map --save

Check out our bower example.

NPM

npm install eon-map --save

Check out our webpack example.

Quickstart

Call eon.map({}). Check out the table of options below for more information.

<div id='map'></div>
<script type="text/javascript">

var channel = 'pubnub-mapbox';

var pn = new PubNub({
  publishKey:   'YOUR_PUB_KEY', // replace with your own pub-key
  subscribeKey: 'YOUR_SUB_KEY'  // replace with your own sub-key
});

var map = eon.map({
  pubnub: pn,
  id: 'map',
  mbToken: 'pk.eyJ1IjoiaWFuamVubmluZ3MiLCJhIjoiZExwb0p5WSJ9.XLi48h-NOyJOCJuu1-h-Jg',
  mbId: 'ianjennings.l896mh2e',
  channels: [channel]
});

</script>

Init

Parameter Value Default
id The ID of the element where the map will be rendered. undefined
channels An array of PubNub channels to subscribe to. Either channels or channelGroups must be supplied. false
channelGroups An array of PubNub channel groups to subscribe to. Either channels or channelGroups must be supplied. false
transform Method for changing the payload format of your stream. function(m){}
history Use PubNub history call to retrieve last message. This will display points at their last known location. Requires PubNub storage to be enabled. false
pubnub An instance of the PUBNUB javascript global. This is required when using your own keys. See the subscribeKey example. false
connect A function to call when PubNub makes a connection. See PubNub subscribe function(){}
marker A custom Mapbox marker object. Use this to change the marker icon, tooltip, etc. L.marker
rotate Add bearing to markers in options.angle. This won't have any effect unless you're using a rotated marker type. false
message A function to call everytime a PubNub message is recieved. See PubNub subscribe function(message, timetoken, channel){}
transform Method for changing the payload format of your stream. See example function(m){return m}
provider Google or Mapbox mapbox
mbToken Mapbox API Token (Mapbox Only). undefined
mbId Mapbox Map ID (MapBox Only). undefined
options An options object supplied to the MapBox Maps constructor (MapBox Only). {}
googleKey Google Maps API Key (Google Maps Only) undefined
googleMutant Configure Google Maps Styles and Options as documented in Google Mutant Plugin { type: 'roadmap'}

Lat/Long Values

eon.map expects an array of objects to be published on the same channel it's subscribed to. More on publishing in the next section.

For example, below you can find a list of all the Torchy's Tacos in Austin, TX.

var torchys = [
  { latlng: [30.370375, -97.756138] },
  { latlng: [30.323118, -97.739144] },
  { latlng: [30.302816, -97.699490] },
  { latlng: [30.293479, -97.742405] },
  { latlng: [30.250337, -97.754593] },
  { latlng: [30.236689, -97.762730] }
];

Publishing Messages

The function below is called connect and fires when the pubnub_mapbox library is ready.

This function uses the included PubNub library to pubnub.publish() packets to the pubnub.subscribe() call waiting inside the Mapbox framework.

Notice how the subscribeKey and channel/channels matches.

function connect() {

  var point = {
    latlng: [37.370375, -97.756138]
  };

  var pn = new PubNub({
    publishKey:   'YOUR_PUB_KEY', // replace with your own pub-key
    subscribeKey: 'YOUR_SUB_KEY'  // replace with your own sub-key
  });

  setInterval(function(){
    var new_point = JSON.parse(JSON.stringify(point));

    new_point.latlng = [
      new_point.latlng[0] + (getNonZeroRandomNumber() * 0.1),
      new_point.latlng[1] + (getNonZeroRandomNumber() * 0.2)
    ];

    pn.publish({
      channel: channel,
      message: [new_point] // even a single point should be an array
    });

  }, 500);

};

var map = eon.map({
  pubnub: pn,
  id: 'map',
  mbToken: 'pk.eyJ1IjoiaWFuamVubmluZ3MiLCJhIjoiZExwb0p5WSJ9.XLi48h-NOyJOCJuu1-h-Jg',
  mbId: 'ianjennings.l896mh2e',
  channels: [channel],
  connect: connect
});

You probably want to publish data from the back-end instead. Check out our docs for more info:

http://www.pubnub.com/documentation/

Following a Point

You can tell the map to follow a point to it's new location whenever data is received by supplying a message callback.

var pn = new PubNub({
  publishKey:   'YOUR_PUB_KEY', // replace with your own pub-key
  subscribeKey: 'YOUR_SUB_KEY'  // replace with your own sub-key
});

var map = eon.map({
  pubnub: pn,
  id: 'map',
  mbId: 'ianjennings.l896mh2e',
  //...
  message: function (data) {
    map.setView(data[3].latlng, 13);
  }
});

Marker Customization

You can supply a custom Mapbox marker object with custom tooltips by extening the L.marker object provided by mapbox. Learn more about custom markers here.

<div id='map'></div>
<script>
  L.RotatedMarker = L.Marker.extend({
    options: { angle: 0 },
    _setPos: function(pos) {
      L.Marker.prototype._setPos.call(this, pos);
      if (L.DomUtil.TRANSFORM) {
        // use the CSS transform rule if available
        this._icon.style[L.DomUtil.TRANSFORM] += ' rotate(' + this.options.angle + 'deg)';
      } else if (L.Browser.ie) {
        // fallback for IE6, IE7, IE8
        var rad = this.options.angle * L.LatLng.DEG_TO_RAD,
        costheta = Math.cos(rad),
        sintheta = Math.sin(rad);
        this._icon.style.filter += ' progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\', M11=' +
          costheta + ', M12=' + (-sintheta) + ', M21=' + sintheta + ', M22=' + costheta + ')';
      }
    }
  });

  var pn = new PubNub({
    publishKey:   'YOUR_PUB_KEY', // replace with your own pub-key
    subscribeKey: 'YOUR_SUB_KEY'  // replace with your own sub-key
  });

  var map = eon.map({
    pubnub: pn,
    id: 'map',
    mbId: 'ianjennings.lec77m70',
    mbToken: 'pk.eyJ1IjoiaWFuamVubmluZ3MiLCJhIjoiZExwb0p5WSJ9.XLi48h-NOyJOCJuu1-h-Jg',
    channels: ['rutgers-bus-data'],
    rotate: true,
    history: true,
    marker: function (latlng, data) {

      var marker = new L.RotatedMarker(latlng, {
        icon: L.icon({
          iconUrl: 'http://i.imgur.com/2fmFQfN.png',
          iconSize: [9, 32]
        })
      });

      marker.bindPopup('Route ' + data.routeTag.toUpperCase());

      return marker;

    }
  });
</script>

Configure using your own PubNub API Keys

Using your own API Key with Eon Maps

You can set the pubnub init parameter when using Eon Maps. This allows you to configure PubNub client connections with extra security options such a auth_key and your cipher_key. You should also set secure: true and ssl: true as well.

<div id="map"></div>
<script>
  var pn  = PUBNUB({
    subscribeKey : 'YOUR_SUB_KEY',
    ssl : true
  });
  var channel = 'my-map';
  var map = eon.map({
    pubnub: pn,  // PubNub goes here
    channels: channel,
    id: 'map',
    mbId 'mapbox.streets',
    mbToken: 'pk.ey31IjoiaWRtc3giLCJhIjoiZZ1zMGI2ZjBlNTMxZjk5YTEwNjM5WNJlOWI4MmJiZGIifQ.U1jMQo2QVeuUtt85oD7hkQ'
  });
</script>

Kitchen Sink

Check out the bus.html and flight.html for full featured examples.

Customizing with Mapbox

The MapBox map object is returned by eon.mapbox and can be customized using the Mapbox API. Also see the Mapbox examples page.

Also note that you can customize your map using Mapbox map editor. You can change the map background style, add static markers, etc. Visit Mapbox for your own API key.

Distributed Systems

The EON library compiles all messages at designated intervals. This means you can publish from multiple sources into one map. For example, you can map the individual locations of 3 phones by supplying the same channel to your PubNub publish requests. The flight example works like this; not every flight is updated on every subscribe call.

eon-map's People

Contributors

darryncampbell-pubnub avatar ianjennings avatar pubnubcraig avatar stephenlb 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  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

eon-map's Issues

Change marker (pop-up / color) based on event

Hi,

I have the following use case:

  • In our office I have a "realtime" EON map that displays markers
  • These markers pop-in whenever one of our customers opens a web-form in our application
  • I would like these markers to dynamically update when e.g. a state changes (timeout / login) or when certain events happen in our web-form.

So far I've succesfully got the map up, and get the markers to show / remove themselves whenever someone logs in or out. The markers also have a little pop-up displaying information about the remote source. All is well here.

What I can't get to work though, is updating properties other than the latlng / position of a marker. I would love to be able to change things like the pop-up, and optionally the marker color or icon.

It appears that the "message" function of the map is called each time an event is published from a remote source, but the "marker" function is not. And it appears that I can only set a custom icon and pop-up in the "marker" function. I don't know how to access the markers properties itself such as the icon, color and pop-up from within the "message" function.

How can I access the properties of the marker that the "message" belongs to so I can customise the marker based on data in the event that I receive? Is that possible?

Lastly it would also be nice if I could somehow "timeout" markers when they don't receive events for e.g. 10 minutes or longer.

Hope you guys are still developing on the EON map and could provide me some pointers here! Thanks a bunch.

Matthijs

  • Amsterdam

eon-map example 'multiple.html' missing comma

The line is missing a ',' after subscribeKey is set:
var pn = new PubNub({
publishKey: 'demo',
subscribeKey: 'demo'
ssl: (('https:' == document.location.protocol) ? true : false)
});

Wildcard subscribe not supported?

I'm trying to build an Application which would allow me to drill-down on viewing devices, so my idea was that I'd have an index in which eon-map would be subscribed to something like "telemetries.*", and then if an specific device was selected eon-map would subscribe to "telemetries.{id}", for example. Trying it out though, it doesn't seem like subscribing like this works. Is this not supported yet or am I just missing something? Thanks!

How to configure with Google maps ?

Getting error when I try to configure with google maps.
Configuration:

var map = eon.map({
      pubnub: pn,
      provider: 'Google',  // tried with 'google' and 'Google' but didn't worked.
      id: 'tracking-map',
      googleKey: 'map_key',  //google map key.
      channels: ['channel']
    });

Error: Please supply a Mapbox Token:

Is it possible for custom html marker popups or onclick listeners for marker popups?

Hi,

This project is awesome, and I'm currently using this framework to build a realtime dispatch system. The web app uses angularjs. So I was wondering if it was possible for a maker popup to have custom html instead of just text. Or, is there an onclick listener for marker popups? I need to show relative information when the person clicks on a popup.

Thanks for helping

Approximate the lo

I have a set of latitude and longitude with their timestamps at which they were captured. I wish to animate a vehicle on the map using these data points. Is there any way to correct the location to the nearest road if the location is a bit away from the road ?

Consider adding support for presence

Goal is to see connected clients on a map.

@pubnubcraig says:

It would be cool to have eon.map/char {…, presence: true, …} and have a transformPresence or just use current transform with channel param passed in. (just off the top of my head)

thing of the possibilities for join, leave/timeout and state-change events and how you would use that to customize the map or chart, like icon animation or color change, etc.

Ian says:
right now the best way is to republish presence events
a user's state parameter would supply the lat / long in the same format as eon
then from there everything would be the same, but maybe like a isPresnece parameter like you suggested in the callbacks

EON Map Critical Issue - Displaying Marker Data

Hi –
Please can you help me. I have been battling with this for days now and is now becoming critical. I am trying to display data in a Marker. I have just short of copied your Flight example and have also tried your Bus Route example.
The minute I try add to the marker.bindPopup(), the form will not render. I have highlighted in Yellow both the Publish and Subscribe
In an effort to hopefully make it easier for you to correct me, please see my code below.
I really appreciate your help.
//////////////// Code//////////
$peccr_code="CSI"; //[peccr_code];
$Qsql="SELECT assetID FROM PECCR_Rescources WHERE peccr_code='".$peccr_code."' AND (availability='Transporting' || availability='Accepted')";
$result = mysql_query($Qsql);
$channels="";
$spacer="', ";
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$channels= $channels."'".($row[0]).$spacer;
// printf ("Name: %s", $row[0]);
}
$channels=trim($channels);
$channels=substr($channels, 0, -1);
?>
DOCTYPE html
Transporting and Accepted Ticket Track
body {
margin: 0;
padding: 0;
}
#map {
position:absolute;
top:0;
bottom:0;
width:100%;
}
function getNonZeroRandomNumber(){
var random = Math.floor(Math.random()199) - 99;
if(random==0) return getNonZeroRandomNumber();
return random;
}
var pubnub = new PubNub({
publishKey: 'pub-c-580cec3e-9217-41d6-becd-78b9b526041a',
subscribeKey: 'sub-c-8baae792-de10-11e6-831c-02ee2ddab7fe'
});
var channels = [];
// create channel groupchannels
pubnub.channelGroups.addChannels(
{
channels: channels,
channelGroup: "sc_tickets"
},
function(status) {
if (status.error) {
console.log("operation failed w/ status: ", status);
} else {
console.log("operation done!")
// list channels
pubnub.channelGroups.listChannels(
{
channelGroup: "sc_tickets"
},
function (status, response) {
if (status.error) {
console.log("operation failed w/ error:", status);
return;
}
console.log("listing push channel for device")
response.channels.forEach( function (channel) {
console.log(channel)
})
}
);
}
}
);
L.RotatedMarker = L.Marker.extend({
options: { angle: 0 },
_setPos: function(pos) {
L.Marker.prototype._setPos.call(this, pos);
if (L.DomUtil.TRANSFORM) {
// use the CSS transform rule if available
this._icon.style[L.DomUtil.TRANSFORM] += ' rotate(' + this.options.angle + 'deg)';
} else if (L.Browser.ie (http://l.browser.ie/) ) {
// fallback for IE6, IE7, IE8
var rad = this.options.angle * L.LatLng.DEG_TO_RAD,
costheta = Math.cos(rad),
sintheta = Math.sin(rad);
this._icon.style.filter += ' progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=' +
costheta + ', M12=' + (-sintheta) + ', M21=' + sintheta + ', M22=' + costheta + ')';
}
}
});
eon.map({
pubnub: pubnub,
id: 'map',
mbToken: 'pk.eyJ1IjoiaWFuamVubmluZ3MiLCJhIjoiZExwb0p5WSJ9.XLi48h-NOyJOCJuu1-h-Jg',
mbId: 'ianjennings.l896mh2e',
channelGroups: ['sc_tickets'],
connect: connect,
rotate: true,
history: false,
marker: function (latlng, data) {
var marker = new L.RotatedMarker(latlng, {
icon: L.icon({
iconUrl: 'https://i.imgur.com/2fmFQfN.png',
iconSize: [9, 32]
})
});
marker.bindPopup('Ticket ' );
return marker;
}
});
function publish(pointId, channel) {
var point = {
latlng: [37.370375, -97.756138]
};
var new_point = JSON.parse(JSON.stringify(point));
new_point.latlng = [
new_point.latlng[0] + (getNonZeroRandomNumber() * 0.05),
new_point.latlng[1] + (getNonZeroRandomNumber() * 0.1)
];
var m = {};
m[pointId] = new_point;
pubnub.publish({
channel: channel,
message: m,
data: ["A33D8C",
37.6271,
-122.3858,
118]
});
}
function connect() {
setInterval(function(){
publish('first', channels[0]);
publish('second', channels[1]);
publish('third', channels[2]);
}, 5000);
};
function getUrlVars() {
var vars = [];
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]
)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
Best regards,
Larry

Bug: pubnub not defined

Thanks for adding channelGroups!

I'm getting an error that pubnub is not defined when I attempt to call eon.map with channelGroups. It's just a typo in pubnub-mapbox.js (it needs to be self.pubnub):

pubnub.channelGroups.listChannels({

Do you have a parameter for "mapbox style"

May I ask, do you have a API for "mapbox style" in eno.map function?

Such as "mbToken" and "mbid" like this:
mbToken: 'pk.eyJ1IjoiaWFuamVubmluZ3MiLCJhIjoiZExwb0p5WSJ9.XLi48h-NOyJOCJuu1-h-Jg'
mbId: 'ianjennings.l896mh2e'

mbId no more possibe? New Mapbox API

It seems impossible to somehow get a working mbId on Mapbox anymore as they changed their API / GUI and there is no more classic Studio...
Maybe its time to upgrade EON Maps to the new Mapbox GL API, where only the accessToken is needed?

How does one display multiple points to the map properly?

How do I have multiple points displayed on the map, all animated when their position is updated, but without passing the array of all location points into the Pubnub channel at once? E.g., if I have three cars I want to track, each car would push up their own location separately. The examples such as https://www.pubnub.com/developers/eon/map/flight/ seem to imply you need to bach all of the location points together. I'd love to know what I'm missing!

One Marker with Path shown

Hi

When using One Marker example how do I also make show a path that a marker traveled? For example show a path using X number of last coordinates. Is it possible ?

Using JSON variable keys is confusing to new developers.

Many new developers are not familiar with the concept of dynamic keys:

var a = "key";
var data = {};
data[a] = true;
console.log(data.key);
// true

It would make sense to provide the option of:

{
    latlng: [1,2,],
    key: 'something'
}

As an option

Adding additional Layers (markers and lines)

Just wondering if you have any examples of adding lines. We have referenced API info for Mapbox but receive errors. Note - we are implementing in Ionic mobile framework

var map = eon.map({
pubnub: pubNub,
id: 'map',
mbToken: this.mbToken,
mbId: this.mbId,
channelGroups: [this.channelGroup],
connect: this.connect(this),
history: false,

  options: {
    zoomAnimation: false,
    tileLayer: 'safetravels.cjln3hfpn3tlb2vs6et264mme-9xcwi',
    featureLayer: function(){
    	var geojson = [
		  {
		    "type": "Feature",
		    "geometry": {
		      "type": "LineString",
		      "coordinates": [
		        [-77.03238901390978,38.913188059745586],
		        [-122.414, 37.776]
		      ]
		    },
		    "properties": {
		      "stroke": "#fc4353",
		      "stroke-width": 5
		    }
		  }
		];
L.geoJson(geojson ).addTo(map);
  }
  },

});

Error:

TypeError: Cannot set property 'accessToken' of undefined
TypeError: Cannot set property 'accessToken' of undefined
at new create (eon.js:9935)
at Object.window.eon.map (eon.js:10169)
at HomePage.webpackJsonp.194.HomePage.ngOnInit

grid.json error

what does it mean if have a ".grid.json" error in my server request? It seems like I have a tile.grid.json file missing, does this have something to do with the eon? how can I make my tile.grid.json file?
mapbox-error

Channel Groups and Distributed Systems

I'm using eon with channelGroups. In the description of Distributed Systems it seems that the intention is for multiple sources to be able to publish to the same channel, and have eon take care of automatically creating the Mapbox markers and updating their positions. For channelGroups, this doesn't seem to be working. I have multiple sources publishing to multiple channels, but all channels are assigned to one channel group. Although eon is receiving all the messages from that channel group, I'm only seeing one marker on the map. I've made sure the messages are arrays as indicated in the documentation.

multiple markers from multiple sources

I want to display multiple markers data coming from multiple channels. is it possible? here's my data structure of my message

[{
latlng: [1.00,1.00]
}]

right now if I initialize my constructor like below, no matter which channels my data comes from, only one marker is rendered on the map and updated

var map = eon.map({
          pubnub: pn,
          id: 'map',
          options: {
          center: [23.7167498, 90.4154881], // [lat, lng]
          zoom: 14,
          },
          mbToken: '....',
          mbId: '....',
          channels: ['bus-01','bus-02']
        });

Cannot get my own pubnub key working on eon-map

I cannot get it working by using the below script, the requetsed url is still "demo" url

http://ps4.pubnub.com/subscribe/demo/my-map/0/0?uuid=some_long_string&pnsdk=PubNub-JS-Web%2F3.7.8

<script>

  var channel = 'my-map';

  eon.map({
    id: 'map',
    mb_token: 'pk.ey31IjoiaWRtc3giLCJhIjoiZZ1zMGI2ZjBlNTMxZjk5YTEwNjM5WNJlOWI4MmJiZGIifQ.U1jMQo2QVeuUtt85oD7hkQ',
    mb_id: 'mapbox.streets',
    subscribe_key: 'my_own_pubnub_sub_key',
    channel: channel
  });

</script>

However if I used the below script, it works

<script>
var output = PUBNUB.$('output')
,   pubnub = PUBNUB.init({ subscribe_key : 'my_own_key' });

pubnub.subscribe({
    channel  : 'my-map',
    callback : function(message) {
        output.innerHTML = [
            JSON.stringify(message), '<br>', output.innerHTML
        ].join('');
    }
});
</script>

The only differences is I am not using eon-map eon.map function.

Could someone please show how to use own pubnub key

Any way to pass options to leaflet?

Is there a way to access the leaflet object when using 'google' provider? Not having this seriously limits functionality we can build, and it shouldn't be so hard to expose it, I imagine, greatly increasing developer freedom to tinker with the maps :)

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.