api bing maps - multi layer (line and pic) on one point - javascript

I can't create multiple layers (images and lines) on the same coordinates.
Does anyone know how you can handle it?
example code:
for (; index_array < array_trip.length; index_array++) {
latVal = array_trip[index_array].latitude;
longVal = Microsoft.Maps.Location.normalizeLongitude(array_trip[index_array].longitude);
map.setView({ center: new Microsoft.Maps.Location(latVal, longVal) });
var pushpinOptions = { icon: path + 'car.png', width: 50, height: 50 };
var pushpin = new Microsoft.Maps.Pushpin({ latitude: latVal, longitude: longVal }, pushpinOptions);
map.entities.push(pushpin);
}

First off, don't set the map view in an array. This will only cause issues. Secondly, ensure that the URL to the pushpin icon is correct. Perhaps try removing that option for now until you see the default pushpins displayed on the map, then try adding a custom icon.
If you want to separate your data into layers you should use EntityCollection's: https://msdn.microsoft.com/en-us/library/gg427616.aspx
Here is a good blog post on layering: https://rbrundritt.wordpress.com/2011/10/13/multiple-pushpins-and-infoboxes-in-bing-maps-v7/

Use could initialize EntityCollection object to add multiple entities to the map at one time.
Example
function GetMap() {
var locations = [
new Microsoft.Maps.Location(60.173783, 24.941068),
new Microsoft.Maps.Location(59.338575, 18.065823),
new Microsoft.Maps.Location(59.922602, 10.749411),
new Microsoft.Maps.Location(55.675817, 12.570452)
];
var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), { credentials: "Bing Maps Key" });
//1. Add pushpins
for (var i = 0; i < locations.length; i++) {
var pin = new Microsoft.Maps.Pushpin(locations[i]);
// Add the pushpin
map.entities.push(pin);
}
//2. Add a polyline
var line = new Microsoft.Maps.Polyline(locations);
map.entities.push(line);
//3. Add a polygon
var polygoncolor = new Microsoft.Maps.Color(100, 100, 0, 100);
var polygon = new Microsoft.Maps.Polygon(locations, { fillColor: polygoncolor, strokeColor: polygoncolor });
map.entities.push(polygon);
var bestview = Microsoft.Maps.LocationRect.fromLocations(locations);
map.setView({ bounds: bestview });
}
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<body onload="GetMap();">
<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>
</body>

Related

Cant get my marker's latLng to use in L.Routing.control

guys
I been trying to get my markers latlon when user double click on it but still don't get any results. Been trying other methods but i think this is the most accurate since i dont get any error when executing js
Any recommendation pls
var places = [
["LOCATION_1", 8.9856146341374, -79.51102268985925],
["LOCATION_2", 8.984640842221594, -79.51383510471848],
["LOCATION_3", 8.972080043026754, -79.5529245611453],
["LOCATION_4", 9.052896045979661, -79.4515923525883],
["LOCATION_5", 9.053366385577624, -79.50832832626823]
];
var map = L.map('map', {
center: [9.352867999999996, -79.689331],//[35.791188, -78.636755],
zoom: 9,
layers:L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
})
});
for (var i = 0; i < places.length; i++) {
marker = new L.marker([places[i][1], places[i][2]])
.bindPopup(places[i][0])
.addTo(map);
}
function getdest(){
L.marker.on('dblclick',function(e){
var latlng_dest=e.latlng() });
console.log(latlng_dest)
return latlng_dest
}
navigator.geolocation.getCurrentPosition(function(location) {
var latlng_orig = new L.LatLng(location.coords.latitude, location.coords.longitude);
L.Routing.control({
waypoints: [
//L.latLng(9.10607301250145, -79.34754531445351),
L.latLng(latlng_orig)
//,L.latLng(latlng_dest)
//,L.latLng(9.100769244670843, -79.35099352767948)
,L.latLng(getdest())
]
}).addTo(map)
});
You have many common things wrong:
e.latlng() is not a function it is a property e.latlng
L.marker.on('dblclick',function(e){ this makes no sense. You creating a new instance of a Marker without coords and then adding a listener to it.
You can't return a value in a function from a listener. The listener is not called at the moment you return the value L.marker.on('dblclick',function(e){ var latlng_dest=e.latlng() }); return latlng_dest
Your code should look like that:
for (var i = 0; i < places.length; i++) {
marker = new L.marker([places[i][1], places[i][2]])
.bindPopup(places[i][0])
.addTo(map)
.on('dblclick', function(e) {
waypoints.push(e.latlng);
routeControl.setWaypoints(waypoints);
});
}
var routeControl = L.Routing.control({
waypoints: [],
}).addTo(map);
var waypoints = [];
navigator.geolocation.getCurrentPosition(function(location) {
var latlng_orig = new L.LatLng(location.coords.latitude, location.coords.longitude);
waypoints.push(latlng_orig);
});

Get five nearest Geolocation names from my position using lat, long

I am trying to display the information depending on user position. So, here I want to display five nearest locations (names) to that user based on his position.
How can I do that, using JavaScript. Help me.
Javascript gives you an ability to get geolocation of the user. That's all.
Geolocation WebAPI
If you want to get some places near your geolocation, you need to use any geo service API such as google maps, or yandex maps and others.
I suggest you to look at this repo: https://github.com/googlemaps/js-store-locator
Additionally, you can see example of what you want here:
https://googlemaps.github.io/js-store-locator/examples/places.html
You need to use the Google Maps Places API:
get the list of places nearby your location
sort them by distance
get 5 nearest places
show them in the list under the map
you need to load two Google Maps libraries: Places and Geometry
and don't forget to get your google maps api key
Here is the code and working fiddle DEMO:
HTML:
<div id="map"></div>
<div id="places"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places,geometry&callback=initMap" async defer></script>
CSS:
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: calc(100% - 200px);
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#places {
background-color: #fff;
height: 200px;
overflow: auto;
padding: 10px 15px;
}
Javascript:
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
var currentLat = -33.867;
var currentLng = 151.195;
var list = document.getElementById('places');
function initMap() {
var currentPoint = {lat: currentLat, lng: currentLng};
map = new google.maps.Map(document.getElementById('map'), {
center: currentPoint,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: currentPoint,
radius: 500,
type: ['store']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var nearestPlaces = getnearestPlaces(results, 5);
for (var i = 0; i < nearestPlaces.length; i++) {
listPlaces(nearestPlaces[i]);
}
}
}
function getnearestPlaces(places, numberOfResults) {
var closest = [];
for (var i = 0; i < places.length; i++) {
var fromPoint = new google.maps.LatLng(currentLat, currentLng);
var toPoint = new google.maps.LatLng(places[i].geometry.location.lat, places[i].geometry.location.lng);
places[i].distance = google.maps.geometry.spherical.computeDistanceBetween(fromPoint, toPoint);
closest.push(places[i]);
}
closest.sort(sortByDist);
return closest.splice(0,numberOfResults);
}
function sortByDist(a, b) {
return (a.distance - b.distance)
}
function listPlaces(place) {
console.log(place);
list.innerHTML += '<p>' + place.name + '</p>';
}
DEMO

IE Issue of Google Maps Marker Animation

I am using google maps api v3.
The Below code i am trying to run , It is working on all Browsers except IE.
Can u please suggest any changes needed to work in IE.
Fiddle Link
My Code is :
var map;
var mapOptions = { center: new google.maps.LatLng(0.0, 0.0), zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP };
var markers = [];
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
from1 = new google.maps.LatLng(0,0);
to1 = new google.maps.LatLng(30,12);
from2 = new google.maps.LatLng(-30,15);
to2 = new google.maps.LatLng(10,-100);
from3 = new google.maps.LatLng(0,-50);
to3 = new google.maps.LatLng(0,50);
addMarker(from1,to1);
addMarker(from2,to2);
addMarker(from3,to3);
}
function addMarker(pos, dest) {
var marker = new google.maps.Marker({
map: map,
position: pos,
destination: dest
});
google.maps.event.addListener(marker, 'click', function(event) {
fromLat = this.position.lat();
fromLng = this.position.lng();
toLat = this.destination.lat();
toLng = this.destination.lng();
// store a LatLng for each step of the animation
frames = [];
for (var percent = 0; percent < 1; percent += 0.01) {
curLat = fromLat + percent * (toLat - fromLat);
curLng = fromLng + percent * (toLng - fromLng);
frames.push(new google.maps.LatLng(curLat, curLng));
}
move = function(marker, latlngs, index, wait, newDestination) {
marker.setPosition(latlngs[index]);
if(index != latlngs.length-1) {
// call the next "frame" of the animation
setTimeout(function() {
move(marker, latlngs, index+1, wait, newDestination);
}, wait);
}
else {
// assign new route
marker.position = marker.destination;
marker.destination = newDestination;
}
}
// begin animation, send back to origin after completion
move(marker, frames, 0, 20, marker.position);
});
markers.push(marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
After some fiddling it looks like a typing issue. Because you haven't implicitly declared the variable frames as a var ie is unsure that it is an array, thus the error "Object does not support method push".
You simply need to change:
frames = [];
to:
var frames = [];
Tested in ie 8- 10.

Remove markers out of viewport

I have to manage a map of about 80.000 markers concentrated in France.
To do that, I decided to get the bounds of the viewport and call a dynamic-JSON (with PHP) which contains the markers inside the viewport. And this on the "idle" event.
I faced a problem with this solution. Indeed, the markers which already exist was re-plotted (at the same position), which consequently weigh the map for nothing...
To solve it, the markers list before and after the JSON query are compared (thanks to jQuery), in order to plot only the new markers. And it works!
Now, I would want to remove the markers which are not currently shown on the map. Or a list of markers (I get it thanks to jQuery) designated by an ID which is also the title of the marker. So, how can a delete markers like that ? I specify that I am using MarkerManager.
Otherwise, you guess that if I do not remove these markers, they will be re-plotted in some cases... For example, you are viewing the city A, you move the map to view the city B, and you get back to the city A...
Here is the code:
var map;
var mgr;
var markers = [];
function initialize(){
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(46.679594, 2.109375)
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var mgrOptions = { borderPadding: 50, maxZoom: 15, trackMarkers: false };
mgr = new MarkerManager(map, mgrOptions);
google.maps.event.addListener(map, 'idle', function() {
mapEvent();
});
}
function mapEvent(){
if( map.getZoom() >= 8 ){
var bounds = map.getBounds();
getSupports(bounds.getNorthEast(), bounds.getSouthWest());
} else {
// Todo
}
}
var markerslistID = new Array();
var markerslistData = {};
function getSupports(ne, sw){
newMarkerslistID = new Array();
newMarkerslistData = {};
// Getting the markers of the current view
$.getJSON('./markerslist.php?nelat='+ne.lat()+'&nelng='+ne.lng()+'&swlat='+sw.lat()+'&swlng='+sw.lng(), function(data) {
for (var i = 0; i < data.points.length; i++) {
var val = data.points[i];
newMarkerslistID.push(val.id);
newMarkerslistData[val.id] = new Array(val.lat, val.lng, val.icon);
}
// List of New Markers TO PLOT
var diffNewMarkers = $(newMarkerslistID).not(markerslistID).get();
// List of Old markers TO REMOVE
var diffOldMarkers = $(markerslistID).not(newMarkerslistID).get();
// Plotting the NEW MARKERS
for( var i = 0; i < diffNewMarkers.length; i++ ){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(newMarkerslistData[diffNewMarkers[i]][0], newMarkerslistData[diffNewMarkers[i]][1]),
title : diffNewMarkers[i],
icon : './images/'+newMarkerslistData[diffNewMarkers[i]][2]+'.png'
});
mgr.addMarker(marker, 0);
}
/*****************************************
HERE WE HAVE TO REMOVE
THE MARKERS CONTAINED IN diffOldMarkers
*****************************************/
mgr.refresh();
// Switching the new list to the old, for the next event
markerslistID = newMarkerslistID;
markerslistData = newMarkerslistData;
});
}
Thank you for your help.
A one-liner to hide all markers that ar not in the current viewport.
!map.getBounds().contains(marker.getPosition()) && marker.setVisible(false);
Or,
if (map.getBounds().contains(marker.getPosition()) && !marker.getVisible()) {
marker.setVisible(true);
}
else if (!map.getBounds().contains(marker.getPosition()) && marker.getVisible()) {
marker.setVisible(false);
}

How to draw polyline in nokia here map using json of lat long in javascript

i am new in using nokia here map, how i can plot json of lat long in nokia here map without marker but it draw polyline..
Here is my code:
$.each(data, function(i, val){
var coord = new nokia.maps.geo.Coordinate(parseFloat(val.latitude),parseFloat(val.longitude));
var markerPolyline = new MarkerPolyline(
coord,
{
polyline: { pen: { strokeColor: "#00F8", lineWidth: 4 } }
}
);
map.objects.add(markerPolyline);
});
I hope you can give some answer.. thanks in advance :)
these are the steps you should follow
1.-Create an array of coordinate objects.
2.-assign those coordinates to the new instance of the polyline
3.-add new polyline to map
example:
var aoCoordinates = []
$(data).each(function(i,val){
var latitude = parseFloat(val.latitude);
var longitude = parseFloat(val.longitude);
//create coordinate object
var coord = new nokia.maps.geo.Coordinate(latitude,longitude);
//add to array
aoCoordinates.push(coord);
})
//after the loop ends create instance of polyline
var markerPolyline = new MarkerPolyline(
aoCoordinates,
{
polyline: { pen: { strokeColor: "#00F8", lineWidth: 4 } },
marker: { brush: { color: "#1080dd" } }
}
);
map.objects.add(markerPolyline);
there are more examples in Nokias Developer page http://developer.here.com/javascript-apis/api-explorer

Categories

Resources