When I need to clear map layer on directionsUpdated seting new driving route or change route by drag & drop, the function map.layers.clear() removes the route line.
Any ideas?
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'Your Bing Maps Key',
center: new Microsoft.Maps.Location(47.606209, -122.332071),
zoom: 12
});
addPushpins();
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function () {
var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
// Set Route Mode to driving
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
var waypoint1 = new Microsoft.Maps.Directions.Waypoint({ address: 'Redmond', location: new Microsoft.Maps.Location(47.67683029174805, -122.1099624633789) });
var waypoint2 = new Microsoft.Maps.Directions.Waypoint({ address: 'Seattle', location: new Microsoft.Maps.Location(47.59977722167969, -122.33458709716797) });
directionsManager.addWaypoint(waypoint1);
directionsManager.addWaypoint(waypoint2);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('printoutPanel') });
directionsManager.calculateDirections();
Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', onUpdateDirections);
});
function onUpdateDirections() {
map.layers.clear();
addPushpins();
}
function addPushpins() {
// Generate an array of 10 random pushpins within current map bounds
var pushpins = Microsoft.Maps.TestDataGenerator.getPushpins(10, map.getBounds());
var layer = new Microsoft.Maps.Layer();
layer.add(pushpins);
map.layers.insert(layer);
}
This is by design. The route data is rendered using a layer of it's own. If you clear all layers on the map, then the directions will disappear as well. For your data, reuse a layer instead like this:
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'Your Bing Maps Key',
center: new Microsoft.Maps.Location(47.606209, -122.332071),
zoom: 12
});
var layer = new Microsoft.Maps.Layer();
map.layers.insert(layer);
addPushpins();
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function () {
var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
// Set Route Mode to driving
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
var waypoint1 = new Microsoft.Maps.Directions.Waypoint({ address: 'Redmond', location: new Microsoft.Maps.Location(47.67683029174805, -122.1099624633789) });
var waypoint2 = new Microsoft.Maps.Directions.Waypoint({ address: 'Seattle', location: new Microsoft.Maps.Location(47.59977722167969, -122.33458709716797) });
directionsManager.addWaypoint(waypoint1);
directionsManager.addWaypoint(waypoint2);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('printoutPanel') });
directionsManager.calculateDirections();
Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', onUpdateDirections);
});
function onUpdateDirections() {
layer.clear();
addPushpins();
}
function addPushpins() {
// Generate an array of 10 random pushpins within current map bounds
var pushpins = Microsoft.Maps.TestDataGenerator.getPushpins(10, map.getBounds());
layer.add(pushpins);
}
Related
I am trying to re create a google heat-map in wps. I managed to have it on a web form but I cannot use any web application only wpf.
How can I inject the code below into a browser control and also passing data from a server side method
<script>
var map, heatmap;
function initMap() {
var CenterLat = 56.816918399;
var CenterLong = -4.1826492694;
var ArrMarkers = [];
var ServerData =<%=GetJsonData(); %>;
var Latitude;
var Longitude;
for (var i = 0; i < ServerData.length; i++) {
Latitude = ServerData[i].Latitude;
Longitude = ServerData[i].Longitude;
var marker = { location: new google.maps.LatLng(Latitude, Longitude) };
ArrMarkers.push(marker);
}
var mapCoordinates = {
center: new google.maps.LatLng(CenterLat, CenterLong),
zoom: 7,
mapTypeId: 'satellite'
};
map = new google.maps.Map(document.getElementById('map'), mapCoordinates);
heatmap = new google.maps.visualization.HeatmapLayer({
data: ArrMarkers,
radius: 15,
opacity: 0.5,
map: map
});
}//end InitMap
function toggleHeatmap() {
heatmap.setMap(heatmap.getMap() ? null : map);
}
</script>
<script type="text/javascript" async defer src="<%=GetJavaScriptUrl()%>">
</script>
So the first script is what google need to produce a staic map with an overlay and the second script is the google API url which also contains the google API key
Some time ago, the map.layers.clear() method would not remove the polyline from the map, but now, after some Bing update, the polyline is being removed when map.layers.clear() is called. How can I solve this?
Map initialize
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'Your Bing Maps Key',
center: new Microsoft.Maps.Location(47.606209, -122.332071),
zoom: 12
});
Here add pushpins
// Add pushpins
function addPushpins() {
// Generate an array of 10 random pushpins within current map bounds
var pushpins = Microsoft.Maps.TestDataGenerator.getPushpins(10, map.getBounds());
var layer = new Microsoft.Maps.Layer();
layer.add(pushpins);
map.layers.insert(layer);
}
Here is update direction callback
// On update directions callback
function onUpdateDirections() {
map.layers.clear();
}
Call addPushpins function
addPushpins();
Here is the Bing Maps Direction Manager sample code
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function() {
var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
// Set Route Mode to driving
directionsManager.setRequestOptions({
routeMode: Microsoft.Maps.Directions.RouteMode.driving
});
// Callback for on update directions
Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', onUpdateDirections);
var waypoint1 = new Microsoft.Maps.Directions.Waypoint({
address: 'Redmond',
location: new Microsoft.Maps.Location(47.67683029174805, -122.1099624633789)
});
var waypoint2 = new Microsoft.Maps.Directions.Waypoint({
address: 'Seattle',
location: new Microsoft.Maps.Location(47.59977722167969, -122.33458709716797)
});
directionsManager.addWaypoint(waypoint1);
directionsManager.addWaypoint(waypoint2);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({
itineraryContainer: document.getElementById('printoutPanel')
});
directionsManager.calculateDirections();
});
UPDATE - Removes partials pushpins
// Map initialize
var map, pushpins, layer;
map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'Your Bing Maps Key',
center: new Microsoft.Maps.Location(47.606209, -122.332071),
zoom: 12
});
// Here is the Bing Maps Direction Manager sample code
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function() {
var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
// Set Route Mode to driving
directionsManager.setRequestOptions({
routeMode: Microsoft.Maps.Directions.RouteMode.driving
});
var waypoint1 = new Microsoft.Maps.Directions.Waypoint({
address: 'Redmond',
location: new Microsoft.Maps.Location(47.67683029174805, -122.1099624633789)
});
var waypoint2 = new Microsoft.Maps.Directions.Waypoint({
address: 'Seattle',
location: new Microsoft.Maps.Location(47.59977722167969, -122.33458709716797)
});
directionsManager.addWaypoint(waypoint1);
directionsManager.addWaypoint(waypoint2);
// Callback for on update directions
Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', onUpdateDirections);
directionsManager.calculateDirections();
});
// On update directions callback
function onUpdateDirections() {
clearLayers();
window.setTimeout(function() {
addPushpins();
}, 2000);
}
// Add pushpins
function addPushpins() {
// Generate an array of 10 random pushpins within current map bounds
pushpins = Microsoft.Maps.TestDataGenerator.getPushpins(10, map.getBounds());
layer = new Microsoft.Maps.Layer();
layer.add(pushpins);
map.layers.insert(layer);
}
// Clear layers
function clearLayers() {
// map.layers.clear();
if (layer !== undefined) {
var currentPrimitives = layer.getPrimitives();
/* remove those that are Pushpins */
for (var i = 0; i < currentPrimitives.length; i++) {
var entity = currentPrimitives[i];
if (entity instanceof Microsoft.Maps.Pushpin){
layer.remove(entity);
}
}
}
}
This is to be expected. It not clearing in the past would have been considered a bug. If you want to clear your layers, but leave the directions you have two options. Clear the layers before calculating the directions, or clear the individual layer rather than all layers in the map.
You could examine your layer, get the primitives from it and remove only the pins. Something like the following:
var currentPrimitives = layer.getPrimitives();
/* remove those that are Pushpins */
for (var i = 0; i < currentPrimitives.length; i++) {
var entity = currentPrimitives[i];
if (entity instanceof Microsoft.Maps.Pushpin){
layer.remove(entity);
}
}
I am working with ionic and i want to display map marker with store logo. I constructed a default marker and I have lots of store pics or logos which need to be placed within the marker show in above image. I have used cordova geolocation plugin for get current location of user.
Response array like this :
var markers = [{
storeName: "Dib Dab Extract",
profilePic: "img/dibdab.png",
address: "420 Mary Jane Way",
rating: "4",
reviews: "4379",
offer: "100 Free Coins with 1st Purchse",
lat: "53.896408",
long: "-105.991427"
}]
Custom Marker Icon :
var image = {
url: 'img/ic_map_pin_gray.png', // image is 512 x 512
scaledSize: new google.maps.Size(80, 80),
};
Marker set on map like this :
var markerPos = new google.maps.LatLng(record.lat, record.long);
// Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos,
icon: image,
});
Issue is resolved using Custom Marker. I have done code like this and i get exact marker like i want in above question. So i posted this answer that help anyone who want custom marker like this. i have refer https://humaan.com/blog/custom-html-markers-google-maps/
// Map Initilize function
function initMap() {
var options = {
timeout: 10000,
enableHighAccuracy: true
};
$cordovaGeolocation.getCurrentPosition(options).then(function(position) {
var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//Wait until the map is loaded
//Load the markers
loadMarkers();
//});
}, function(error) {
console.log(error);
console.log("Could not get location");
//Load the markers
loadMarkers();
});
}
//load marker using rest api
function loadMarkers() {
CommonService.ShowLoader();
YOUR REST API SERVICE.then(function(res) {
angular.forEach(res, function(value, key) {
var record = value;
console.log(record);
var image = {
url: 'img/ic_map_pin_gray.png', // custom background image (marker pin)
scaledSize: new google.maps.Size(70, 70),
};
var markerPos = new google.maps.LatLng(record.lat, record.long);
//Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos,
icon: image,
});
var img_src = record.profilePic;
var overlay = new CustomMarker(
markerPos,
map, {image: img_src}
);
});
}).catch(function(error, status, headers, config) {
console.log(error);
});
}
//CustomMarker function
function CustomMarker(latlng, map, args) {
this.latlng = latlng;
this.args = args;
this.setMap(map);
}
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.draw = function() {
var self = this;
var div = this.div;
if (!div) {
div = this.div = document.createElement('img');
div.src = self.args.image;
div.className = 'marker';
div.style.position = 'absolute';
div.style.cursor = 'pointer';
div.style.width = '35px';
div.style.height = '35px';
div.style.borderRadius = '50%';
if (typeof(self.args.marker_id) !== 'undefined') {
div.dataset.marker_id = self.args.marker_id;
}
google.maps.event.addDomListener(div, "click", function(event) {
google.maps.event.trigger(self, "click");
});
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
}
var point = this.getProjection().fromLatLngToDivPixel(this.latlng);
if (point) {
div.style.left = (point.x - 18) + 'px'; // set custom (i set it as i want to set in map )
div.style.top = (point.y - 56) + 'px'; //set custom (i set it as i want to set in map )
}
};
This worked for me.
marker = new MarkerWithLabel({
position: new google.maps.LatLng(item.latitude, item.longitude),
animation: google.maps.Animation.DROP,
labelContent: "My Job Location",
labelAnchor: new google.maps.Point(10, 38),
labelClass: "markLabelsJob", // the CSS class for the label
labelInBackground: false,
icon: 'img/active-job-pin.png',
map: map
});
Although I got this working in Gmapv2..version three is proving to be a little trickier.
I wanted to add the other attributes into the infobubble from the XML file, but whereever I try and add them, it breaks the on-click marker?
<script type="text/javascript">
var infowindow;
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(54.046575, -2.8007399);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("http://www.xxxxxx.com/xxxxx.com/server/venue_output.php", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var event_name = markers[i].getAttribute("event_title");
var event_start = markers[i].getAttribute("event_start");
var event_link = markers[i].getAttribute("event_link");
var marker = createMarker(markers[i].getAttribute("event_name"),latlng);
}
});
}
function createMarker(name, latlng) {
var marker = new google.maps.Marker({position: latlng, map: map, bounce:true, icon : new google.maps.MarkerImage('http://www.gigizmo.com/gigizmo.com/app/images/marker.png')});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: "<b>" + name + "</b>" });
infowindow.open(map, marker);
});
return marker;
}
</script>
How do I add my javascript values such as event_link to this marker window?
infowindow = new google.maps.InfoWindow({content: "<b>" + name + "</b>" });
You may try this code snippet, provided at : this example
function createMarker(..){
eval(" infowindow"+time+" = new google.maps.InfoWindow({ content: pt.latLng.toString() });");
eval(" marker"+time+" = new google.maps.Marker({ position: pt.latLng, map: map });");
eval(" google.maps.event.addListener(marker"+time+", \"click\", function() { infowindow"+time+".open(map, marker"+time+"); });");
time++;
//rest of your code
}
And also, speaking of my previous experiences:
be sure that your XML file does not include linebreaks.
Especially as the value you set to "name" variable.
I am trying to make an application which displays a map with your current location marker and several markers related to data from the server which location is closed to your current location. So far I can render the map, show the current location and get the data related to this location. The problem arise when I try to add markers about the location of this data.
I´ve read through a lot of forums and pages but I found no solution.
I use this piece of code to add markers (to try to add them ..):
var marker = new google.maps.Marker({
map: map._map,
position: new google.maps.LatLng(bookletMarker[i].location[1],bookletMarker[i].location[0]),
title : bookletMarker[i].title,
draggable:false,
icon: "point.png"
});
//This code renders a map with 2 points and displays the route to travel from point A to point B
//On Map Render
onMapMaprender: function(map, gmap, eOpts) {
var record = Ext.getCmp('Panel').getData();
var map = Ext.ComponentQuery.query('#LocationMap')[0].getMap();
var polyline = new google.maps.Polyline();
var markerImage = new google.maps.MarkerImage(
'marker.png',
new google.maps.Size(32, 31),
new google.maps.Point(0, 0),
new google.maps.Point(16, 31)
);
var lat = record.data.latitude;
var lon = record.data.longitude;
console.log(lat,lon);
var destinationMarker = new google.maps.Marker({
icon: markerImage,
position: new google.maps.LatLng(lat,lon),
title : 'destination',
map: map,
})
var latSrc = localStorage.getItem('lat');
var lonSrc = localStorage.getItem('lon');
var sourceMarker = new google.maps.Marker({
icon: markerImage,
position: new google.maps.LatLng(latSrc,lonSrc),
title : 'source',
map: map,
})
function dir_callback(a,b){
g=a;
route_no=0;
if(b=="OK"){
var polyarr = a.routes[route_no].overview_path;
polyline.setPath(polyarr);
polyline.setMap(map);
}
}
var dirS = new google.maps.DirectionsService();
var req = {
origin: sourceMarker.getPosition(),
destination: destinationMarker.getPosition(),
travelMode: google.maps.DirectionsTravelMode.DRIVING,
provideRouteAlternatives : true
};
dirS.route(req,dir_callback);
},
//Setting the Map
var cr = new google.maps.LatLng(lat,lon);
Ext.getCmp('LocationMap').setMapCenter(cr);
You should be able to get the map instance from your map with getMap() and then add the pointer as described in the google maps api docs:
marker.setMap(map);
You can use map.getMap() to get the google map instance and use it when you create markers.
Here, you have directly added icon image path, instead use MarkerImage object as follow,
var imageIcon = new google.maps.MarkerImage(
"point.png",
new google.maps.Size(32, 32),
new google.maps.Point(0, 0),
new google.maps.Point(16, 31)
);
var marker = new google.maps.Marker({
map: map._map,
position: new google.maps.LatLng(bookletMarker[i].location[1],bookletMarker[i].location[0]),
title : bookletMarker[i].title,
draggable:false,
icon: imageIcon
});