Bing Maps Infobox - javascript

I have created multiple infoboxes using BingMaps V8 API.
The issue that I am facing here is when the infobox is towards the corners of the map, the details from infobox is trimmed.
infobox being trimmed. I want to autopan the :
Code :
var ParseLatLogXml = function(xml, address){
if(typeof xml.resourceSets["0"].resources === "undefined" || xml.resourceSets["0"].resources.length === 0)
{
console.log("Lat Long of Address not found: " + address);
return [];
}
return [ xml.resourceSets["0"].resources["0"].geocodePoints["0"].coordinates["0"],
xml.resourceSets["0"].resources["0"].geocodePoints["0"].coordinates["1"] ];
};
var AddStore = function( storeNumb ,storeID, storeName, city, state, addr, phone, zip, distance, lat, long){
var _loc = new Microsoft.Maps.Location(parseFloat(lat), parseFloat(long));
var _pin = new Microsoft.Maps.Pushpin(_loc, {
icon: '-/media/1044109b112b479bb98e4daf6154e817.ashx',
anchor: new Microsoft.Maps.Point(20, 20)
}
);
var adder = addr + '\r\n' + city + '\r\n' + zip + state + "\r\n" + storeName
// Create the infobox for the pushpin
var _infoBox = new Microsoft.Maps.Infobox(_pin.getLocation(),
{ width: 300,
height: 150,
title: storeName,
description: distance + " miles" +'<br>' + addr +'<br>'+ city + " "+ zip +'<br>'+ phone ,
offset: new Microsoft.Maps.Point(10,15),
showCloseButton: false,
visible: false
});
// Add handler for the pushpin click event.
// Microsoft.Maps.Events.addHandler(_pin, 'click', displayInfobox);
Microsoft.Maps.Events.addHandler(_pin, 'mouseover', function () {
_infoBox.setOptions({ autoPan:true, visible: true });
});
Microsoft.Maps.Events.addHandler(_pin, 'mouseout', function () {
_infoBox.setOptions({ autoPan:true, visible: false });
});
map.entities.push(_pin); //[locNum]
_infoBox.setMap(map);
I tried using the auto pan which i am not sure if it would do the trick.
Can someone help me on this.
I also tried the re-positioning of the ifobox and that dinot help either.
I used below links for reference :
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/cf803dd2-0f56-429e-863b-9f9a6480ff17/bing-maps-v8-api-repositioning-an-infobox?forum=bingmapsajax

There is no built in autopan or repositioning logic in the Infobox class in Bing Maps. The easiest solution would be to center the map on the pushpin when opening the infobox, although this would be better suited if using a click event to open the infobox rather than a mouseover event. Using mouseover/mouseout events would result in the infobox closing if the infoboxes position was changed.
Another option is to use the Custom Infobox module here: http://bingmapsv7modules.codeplex.com/wikipage?title=Custom%20Infobox%20Control The infobox in this module repositions how it is displayed based on where in the map the pushpin is. If the pushpin is in the top right corner, the infobox displays itself to the bottom left of the pushpin. You can find the source code for this module here: http://bingmapsv7modules.codeplex.com/SourceControl/latest#BMv7Plugins/BMv7.CustomInfobox/scripts/V7CustomInfobox.js

Related

Onclick infobox - bing map api

I'm having trouble getting the infoboxes for the bing API to open on click from outside the map.
Here is the show infobox function and the function to create the pin/infobox itself:
function displayInfobox(e) {
pinInfobox.setOptions({
title: e.target.Title,
description: e.target.Description,
visible: true,
offset: new Microsoft.Maps.Point(0, 25)
});
pinInfobox.setLocation(e.target.getLocation());
}
function hideInfobox(e) {
pinInfobox.setOptions({
visible: false
});
}
function displayPinsOnMap(results) {
// Creates a collection to store multiple pins
var pins = new Microsoft.Maps.EntityCollection();
//Create the info box for pushpin
var infoboxOptions = {width: 260, height:160};
pinInfobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), infoboxOptions);
infoboxLayer.push(pinInfobox);
// Create Pins
for (var i = 0; i < results.length; i++) {
//pushpin location
var position = new Microsoft.Maps.Location(results[i]["Lat"], results[i]["Lon"]);
//Create the pin
if(results[i]["DNC"] == 'DNC') {
var sppins = {htmlContent:"<img src='badsp.png' height='32px'> " };
} else {
var sppins = {htmlContent:"<img src='sppin.png' height='32px'> " };
}
var pin = new Microsoft.Maps.Pushpin(position, sppins);
pin.Title = results[i]["Business Name"];
pin.Description =results[i]["Address"] + "<br>" +
results[i]["City"] + ", " +
results[i]["StateListing"] + "<br>" +
results[i]["Phone"] +
"<br>Fax: " + results[i]["Fax"] +
"<br>Email: " + results[i]["Email"];
Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);
function pinclick(i) {
Microsoft.Maps.Events.addHandler(results[i], 'click');
}
//Add pin to the map
map.entities.push(pin);
}
//hide box on map move
Microsoft.Maps.Events.addHandler(map, 'viewchange', hideInfobox);
//add pins/infobox
map.entities.push(pinInfobox);
}
I have a list of items pulled from a JSON file and displayed on the map. Each item creates a pin and info box as well as in a table off to the side of the map. What I need to be able to do is on click of the name of the company from the table I need it to open up the infobox associated with that company. Here is how I did it in the past with Google API - this doesn't seem to work in the same way for Bing (yes I have to use bing).
"<td>"+'<a href="#" onclick="javascript:displayInfobox(' + (i) + ');">' + results[i]["Business Name"] +'<\/a>' + "</td>"
It looks like you have copied the displayInfobox function from some code that is expecting to be trigerred when someone clicks a pushpin because that function has this code:
pinInfobox.setLocation(e.target.getLocation());
the getLocation() method exists on Bing Maps pushpin object but obviously not on your so it will be failing when it gets to that line (your using your browsers debug tools right?). You will need to change that line so that it gets the location for the infobox to show from somewhere, either by having the lat lon as some attribute on your and constructing a new Bing Maps location object using those or by looping through all the pins on the map to find that one that matches your in some way

GoogleMap. Markers icon image dissapear and/or overlap them

Since last monday we have problem in google maps. First of all, we use custom markers to show the results of a search "grouped" by concept, that's mean than we show a yellow box with a text and a number with its count. If you take a look at this image you will see the errors
(Link to the image at http://imgur.com/sa1PvQo )
In "Grierkenland (556)" or "Turkije (392)" markers there aren't any kind of image there (behold the red boxes)
In "Cyrpus (43)" you will see the image than i put in each marker but only on this marker appears. Appears too FOUR more images overlaped one each other (numbers 1 to 4 on the screenshot, the original image is the number 1, the rest is the same image overlap on each other)
We don't change anything for a month and, i said before, from this monday the marker's image doesnt work at all. Our code are:
Create the icon. Generates an object with the image's url (the pathPrefix is a string with some like "www.test.com", for ex.):
getLocIcon: function (markerLength) {
var markerSize = 100;
if (markerLength > 18) {
markerSize = 183;
} else if (markerLength > 15) {
markerSize = 146;
} else if (markerLength > 13) {
markerSize = 122;
}
icon =
{
url: priv.pathPrefix + '/images/googlemaps/loc-marker-' + markerSize + '.png',
anchor: new google.maps.Point(15, 0),
size: new google.maps.Size(markerSize, 22)
};
return icon;
},
Create the marker. Generates a marker object with all the information required, including the "icon" object:
createLinkMarker: function (gllPosition, strTargetText, strTargetLink, strMarkerToolTip) {
var locationMarkerText = "<nobr>" + strMarkerToolTip + " (" + strTargetText + ")</nobr>";
var otherOpts =
{
position: gllPosition,
map: priv.googleMap,
labelClass: "locationLabel",
icon: priv.getLocIcon((strMarkerToolTip + " (" + strTargetText + ")").length),
clickable: true,
draggable: false,
labelContent: locationMarkerText,
//anchorPoint: new google.maps.Point(15, 0),
title: strMarkerToolTip
};
var marker = new MarkerWithLabel(otherOpts);
google.maps.event.addListener(marker, 'click', function () {
location.href = strTargetLink;
});
return marker;
},
The rest of the code to include the markers inside google maps (priv.googleMap is the google map's object and markers are an array of marker getted from createLinkMarker function):
var markerMgrOptions = { maxZoom: priv.maxZoom, trackMarkers: false };
priv.markerManager = new MarkerManager(priv.googleMap, markerMgrOptions);
[ ... ]
priv.markerManager.clearMarkers();
priv.markerManager.addMarkers(markers, priv.minZoom, priv.maxZoom);
priv.markerManager.refresh();
Do you know if there are something new or a bad practice there?
Thanks in advance and regards.

How to display newer Google Map InfoWindows on top of older ones

I am having Google Map with InfoWindows being added dynamically. The issue is, when two InfoWindows overlap, the recent one won't always be on top of older ones.
How can I make sure latter InfoWindow always show up on top of all other InfoWIndows using Javascript/jQuery?
The InfoWindows are added when I receive new images and coordinates through websocket. Here is my code:
function addToMap(image) {
console.log("In addToMap...");
coordinates = image[2].split(',');
pin=new google.maps.LatLng(coordinates[0], coordinates[1]);
if(marker) {
marker.setMap(null);
}
var markerIcon = image_car_icon;
marker=new google.maps.Marker({
position:pin,
zIndexProcess: function( m )
{
return 9999999 + pin_count;
},
icon:markerIcon
});
marker.setMap(map);
map.setCenter(marker.getPosition());
pin_count++;
if(image[0] != "NOP") {
popup = new google.maps.InfoWindow({
content:'<image id="pin_' + pin_count + '" src="data:image/png;base64,' + image[1] +'"/>',
});
popup.open(map, marker);
}
}
popup is the InfoWindow created when I get a new image. Suppose two images have almost same coordinates, I want the second InfoWindow to be on top (z-index). But, most of the time, the first window stays on top.
I have found out a solution. I am manually modifying the z-index of the marker by using the image as the handle. marker_count is a running marker, so the z-index will be greater than the previous marker.
google.maps.event.addListener(popup, 'domready', function() {
console.log("DOM READY...........................");
// Bring latest Image to top
e = $('#pin_' + img_count).parent().parent().parent().parent();
e.css({
'z-index' : (99999 + marker_count),
});
});

Zoom in into a marker using JavaScript link

I'm a beginner in google maps and JavaScript.
I'm creating a random markers on google map using Maps API V3, I want to create a list on the side that contain all Markers Id so when i click on Marker ID it will zoom in, on the map to show the marker. specifically i want to know how to create that link in javascript
thank you
This answer is from beginner to beginner ;) I like benastan's answer for succinctness and the application of closure, still I'd like to show a more "basic" approach by writing functions.
I don't feel qualified to talk about closures and function scopes, but I can say from experience these closure "wrappers" prevent unexpected behavior from functions called within loops or within other functions. One such bug could be a loop iterator value ending up all the same value (last iteration) or undefined. (my own example)
Link to full code: http://jsfiddle.net/WaWBw/
Click on the map to place markers, and clicking on markers or links on the side zooms in.
function addMarker(pos) {
var marker = new google.maps.Marker({
map: map,
position: pos
});
markers.push(marker);
count = markers.length - 1;
addMarkerListener(marker, count, 6);
makeDiv(count, 4, "Marker #");
count++;
}
function addMarkerListener(marker, index, zoomLevel) {
google.maps.event.addListener(marker, 'click', function(event) {
zoomIn(index, zoomLevel);
});
}
function makeDiv(index, zoomLevel, content) {
document.getElementById("sidebar").innerHTML += '<div onclick="zoomIn(' + index + ',' + zoomLevel + ')">' + content + ' ' + index + '</div>';
}
function zoomIn(index, zoomLevel) {
map.setCenter(markers[index].getPosition());
map.setZoom(zoomLevel);
}
Say you have a set of lat/lng coordinates:
var coords = [[32, -70], [50, -10], [0, 20]];
Loop through the coordinates, plotting the marker on your map and generating the list items. Bind the click handler at the same time:
var tpl = 'Click here to view a point';
// Loop through coordinates.
for (var i in coords) {
// Create a closure.
(function() {
var pt = coords[i],
latlng = new google.maps.LatLng(pt[0], pt[1]),
marker = new google.maps.Marker({
position: latlng,
map: map // variable containing your google map.
}),
elm = document.createElement('li');
elm.innerHTML = tpl;
// When you click the list item, set map center to latlng of marker.
elm.onclick = function() {
map.setCenter(latlng);
};
document.body.appendChild(elm);
})();
}

Google Maps V3 JavaScript works only in Chrome?

I wrote a script that first geocodes an address and then displays a map of that address.
The trouble is, it only works in Chrome / Chromium. Other browsers (Firefox 10 & IE9) display a grey box. A problem that could be related, if I add a marker to the map, the marker does not show in Chrome.
I know that :
I connect with the API successfully with my API key.
The address is properly geocoded.
I use jQuery UI dialog to display the map. This, however, does not seem to be a problem. Removing the dialog and using a static div creates the same "grey box" result.
Below is my script, how I invoke it, and the website that I am using this on.
Here's the script:
function Map(properties)
{
var that = this;
// the HTML div
this.element = properties.element;
// address string to geocode
this.address = properties.address;
// title to use on the map and on the jQuery dialog
this.title = properties.title;
this.latlng = null;
this.map = null;
this.markers = [];
// geocode address and callback
new google.maps.Geocoder().geocode({'address': this.address}, function(data)
{
// geocoded latitude / longitude object
that.latlng = data[0].geometry.location;
// map options
var options =
{
zoom: 16,
center: that.latlng,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create a map
that.map = new google.maps.Map(that.element, options);
// add a marker
that.markers.push(new google.maps.Marker({map: that.map,
position: that.latlng,
title: that.title + "\n" +
that.address}));
});
this.get_google_map = function()
{
return that.map;
}
// creates a jQuery UI dialog with a map
this.show_in_dialog = function()
{
// because the dialog can resize, we need to inform the map about this
$(that.element).dialog({ width: 400, height: 300, title: that.title,
resizeStop: function(event)
{
google.maps.event.trigger(that.map, 'resize');
},
open: function(event)
{
google.maps.event.trigger(that.map, 'resize');
}});
}
this.center = function()
{
that.map.setCenter(that.latlng);
}
}
Here's how I invoke it :
// grab the address via HTML5 attribute
var address = $("#address").attr("data-address");
// ... and the title
var title = $("#address").attr("data-title") + " Map";
var map_element = document.createElement('div');
// append the newly created element to the body
$("body").append(map_element);
// create my own map object
var map = new Map({ element : map_element,
address : address,
title : title });
// bind a link to show the map
$("#map_link").click(function()
{
map.center();
map.show_in_dialog();
return false;
});
And here's the URL of the problem (click on map):
http://testing.fordservicecoupons.com/dealer/30000/premium_coupon_page
Last but not least, I combine and obfuscate my JavaScripts, so what you see above is not exactly the same as in the source on the website.
This doesn't look good:
resizeStop: function(event) { google.maps.event.trigger(that.element, 'resize'); },
open: function(event) { google.maps.event.trigger(that.element, 'resize'); }
you trigger the resize-event on the element that contains the map(that.element), but you must trigger resize on the google.maps.Map-object (what should be that.map in this case)
Wow... Here was the issue.
The layout that I built was a fluid layout. So, one of the first CSS rules that I have written was:
img, div { max-width: 100%; }
So that divs and images can scale. Well, for whatever reason, Google maps DOES NOT like this rule with the end result being a grey box.
And so I added another rule - an exception for Google maps:
img.no_fluid, div.no_fluid { max-width: none; }
And then, in javascript:
// AFTER DIALOG CREATION
$(dialog).find('*').addClass("no_fluid");
The find('*') will get us all the descendants.
Viola!

Categories