GoogleMap. Markers icon image dissapear and/or overlap them - javascript

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.

Related

How to get geojson property using getelementbyid based on marker from geolocation?

I am having trouble creating a function, and hope I am explaining this correctly since I am new to working with geojsons in this capacity.
I am creating an app which captures information based on geolocation. Below is a snippet of the code saved as main.js, which I read into my index.html file (farther below). I am able to use document.getElementByID to capture coordinates of a marker based on geolocation. I am also able to use a circle I created to determine if the marker is within (true) or outside (false) of the circle.
I am having trouble reading in a geojson of polygons and getting the name (geoid of census tract) based on the marker location. I have no trouble reading in the geojson, which I saved as a variable in PA2020Census.js. I am also able to use a click event to capture the geojson's name. However, I would like to not use the click event, and instead capture the name within the getposition function.
How would I go about this? I think I need to read in the geojson as a .geojson instead of a .js. Or can I use the variable name and create a function within the getposition function? Apologize if my description is vague, I feel like I'm close but have hit a wall. Thank you.
Code within "main.js"
L.Control.geocoder().addTo(map);
if (!navigator.geolocation) {console.log("Your browser doesn't support geolocation feature!");} else {
setInterval(() => {navigator.geolocation.getCurrentPosition(getPosition);}, 8000);}
var markers, circles, lat, long, accuracy;
var trackingPath = [];
function getPosition(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
accuracy = position.coords.accuracy;
markers = L.marker([lat, long],{draggable: false});
circles = L.circle([lat, long], { radius: accuracy });
document.getElementById('latitude').value = markers.getLatLng().lat;
document.getElementById('longitude').value = markers.getLatLng().lng;
var featureGroup = L.featureGroup([markers]).addTo(map);
map.fitBounds(featureGroup.getBounds());
trackingPath.push([markers, circles]);
var d = map.distance(markers._latlng, circle.getLatLng());
var isInside = d < circle.getRadius();
circle.setStyle({fillColor: isInside ? 'green' : 'red '});
document.getElementById('Geofence').value = isInside;
console.log("Your coordinate is: Lat: " + lat + " Long: " + long + " Accuracy: " + accuracy);
}
var circle = L.circle([39.936100074828076, -75.19797365410456], {
color: '#E9967A',
fillColor: ' ',
fillOpacity: 0.5,
radius: 120
}).addTo(map);
code within index.html
<script src= "js/main.js"></script>
<script src= "js/PA2020Census.js"></script>
<script>
var myStyle = {"color": " #8B8989", "weight": 2,"opacity": 1.5};
function onEachFeature(feature, layer) {layer.on('click', function ()
{document.getElementById('census').value = layer.feature.properties.GEOID;});
};
var PA2020Census = L.geoJSON(PA2020Census, {
onEachFeature: onEachFeature,
style: myStyle,
}).bindPopup(function (layer) {
return "Census Tract: " + layer.feature.properties.GEOID
}).addTo(map);
</script>
I have tried event listeners to successfully use "click", but would like to get the geojson's property name based on geolocation.

Bing Maps Infobox

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

overlapping feature order google maps

How do I programatically in javascript define which feature is on top of another when they overlap
In This picture I clicked on the smaller geographic feature, however the information for the outer geographic feature came up. I would like to programmatically put the smaller features on top.
Here is the my code to populate the map in javascript-
map.data.loadGeoJson('<path to my geojson definition>');
map.data.setStyle(function (feature) {
let color = 'gray';
console.log(feature);
if (feature.getProperty('isColorful')) {
color = 'blue';
}
return ({
fillColor: color,
strokeColor: color,
strokeWeight: 1
});
});
map.data.addListener('click', function (event) {
let name = event.feature.getProperty('name');
let contentString = '<h4>Polygon Info</h4><br>';
contentString += '<p>';
if (name) {
contentString += '<b>Name:</b>' + name + '<br>';
}
contentString += '</p>';
let infowindow = new google.maps.InfoWindow({
content: contentString,
position: event.latLng
});
infowindow.open(map);
event.feature.setProperty('isColorful', true);
});
Note I reversed the order of the features in the geojson file itself and that did not change the behavior.
You can use the z-index property of feature.Assuming you can disinguish one feature entry from another you can adjust z-index depending on your need in setStyle() function, just work out appropriate values
return ({
fillColor: color,
strokeColor: color,
strokeWeight: 1,
zIndex: zIndex
});
Or update z-index when mouse enters
map.data.addListener('mouseover', function(e) {
map.data.overrideStyle(e.feature, {
//strokeColor: '#1e3a2a',
//strokeWeight: 2, /* can also change these like hover effect */
zIndex: 6
});
});
map.data.addListener('mouseout', function(e) {
map.data.revertStyle();
});

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

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);
})();
}

Categories