I am using draggable markers in google maps. I have to get the position of markers after dragging because i have to store the new position of marker
The code is
var m = new GMarker(point,{draggable: true});
m.entry_id = id;
m.isMarker = true;
app.entries[id].marker = m;
Here is my example that will display the new location of the marker in and info-window at the new location after the marker has been dragged:
//assuming u have lat and long as latitude and longitude of the initial position
var location = new GLatLng(lat,long);
var marker = new GMarker(location, {draggable: true});
GEvent.addListener(marker, "dragstart", function() {
map.closeInfoWindow();
});
GEvent.addListener(marker, "dragend", function() {
var latlng = marker.getLatLng();
marker.openInfoWindowHtml("New Lat : " + latlng.lat() + ", New Long : " + atlng.lng() );
});
Am assuming you are using API version 2, the solution is a bit different for Version 3, but just a matter of change in the calling conventions sort of.
Related
I have an array like this deviceId = [005305230001JIZZZZ, 085835360001NBGJZZ, 085835360002NBGJZZ].
The info window should show the deviceId and be displayed based on which marker is clicked. I started looking at JavaScript only a few days back and can't understand how the functions work and dont have the time right now to learn becauseI have to get this done. I saw a few implementations on this, but I think they have done the adding multiple markers differently using functions, I think. I couldn't understand it so I used for loop.
The latArray and lngArray have something like this [12.1456,12.5256,11.566] and [72.145,72.4557,75.23535]
I cant figure out how to add info windows for corresponding markers.
This is the code for map:
function initMap() {
var bounds = new google.maps.LatLngBounds();
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv);
map.setCenter(new google.maps.LatLng(latArray[0],lngArray[0]));
map.setZoom(18);
for(i=0;i<latArray.length;i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(latArray[i],lngArray[i]),
map: map,
title:"This is the place.",
// icon:"phone4.png"
});
//bounds.extend(marker.getPosition());
console.log(latArray);
console.log(lngArray);
}
//map.fitBounds(bounds);
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
How to show info window of corresponding markers.
This is content for marker:
contentString = '<div id = "content>'
+'<p style = "color:#000000">DeviceID<p>' +
'<p>'+ deviceId[i] + '<br></p>' //deviceId is the array with content
+ '</div>'
I read something about closures but didn't understand. Please help
Edit: I just tried this. I'm getting js?callback=initMap:34 InvalidValueError: setPosition: not a LatLng or LatLngLiteral: not an Object
What i tried:
var markerArray=[];
for(i=0;i<latArray.length;i++)
{
markerArray.push("new google.maps.LatLng("+ latArray[i]+","+lngArray[i]+")");
console.log(markerArray[i]);
}
console.log(markerArray[0]);
for(i=0;i<latArray.length;i++)
{
marker = new google.maps.Marker({
position: markerArray[i],
map: map,
title:"This is the place.",
// icon:"phone4.png"
});
var infoWindow = new google.maps.InfoWindow({
content: contentString[i]
});
marker.addListener('click', function(marker,contentString) {
infoWindow.open(map, marker);
});
}
So I will not bother you with the explanation how closures work (as you are saying your not interested in it now), I just supply you the solution:
// Your arrays with geo informations
var latArray = [-25.363, -26.263, -25.163];
var lngArray = [131.044, 131.144, 132.044];
// Your array with device information
var deviceIdArray = ["AAA", "BBB", "CCC"];
// Just create map according to the first geo info
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: latArray[0], lng: lngArray[0]},
zoom: 6
});
// Loop throuhg all geo info
latArray.forEach(function(lat, i) {
// For each one create info window
var infoWindow = new google.maps.InfoWindow({
content: '<div id="content>'
+ '<p style="color:#000000">DeviceID<p>'
+ '<p>'+ deviceIdArray[i] + '</p>'
+'</div>'
});
// For each one create marker
var marker = new google.maps.Marker({
map: map,
position: {lat: latArray[i], lng: lngArray[i]}
});
// Click on the currently created marker will show the right info window
marker.addListener("click", function() {
infoWindow.open(map, marker);
});
});
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map"></div>
Take a look at my function with map. It takes json object with some data from PHP and 'translate' it into array and then adds content to multiple markers (it is not dynamic in real time - you have to reload page). In addition it has a search box (which opens certain info window). If you don't understand do not hestitate to ask :).
//check if document is fully loaded, seetting a container for ajax call results
$(document).ready(function() {
var tablica = [];
// ajax call for action preparing set of names, descriptions, coords and slugs needed to render deatiled markers on map
$.ajax({
url: 'map/json_prepare',
dataType: 'json',
success: function(response) {
var obj = JSON && JSON.parse(response) || $.parseJSON(response);
obj.forEach(function(item, index, array)
{
tablica.push(item);
});
//call a function rendering a map itself
var map;
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.06561980, lng: 19.946850},
zoom: 12
});
////////////////////////////////////////////////////////////////////////////////////////////////////
// LOOP ADDING MARKERS FROM DB WITH PROPER INFO WINDOWS (DESCRIPTION AND LINKS)
// Add a markers reference
var markers = [];
$.each(tablica, function( key, value ) {
//markers
var myLatLng = {lat: value[1], lng: value[2]};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: value[0],
clickable: true,
animation: google.maps.Animation.DROP,
adress: value[5]
});
//infowindows
marker.info = new google.maps.InfoWindow ({
content: '<h1>'+ value[0] + '</h1>' + '<br>' + '<br>' + value[3] + '<br>' + value[5] +'<br>' + '<br>' + '' + 'Details' + '<br/>' +
'' + 'Take part in' + '<br>'
});
//eventlistener - after click infowindow opens
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
//event listener - after dblclick zoom on certain event is set
google.maps.event.addListener(marker, 'dblclick', function() {
map.setZoom(18);
map.setCenter(marker.getPosition());
});
markers.push(marker);
});
// End of loop adding markers from db.
///////////////////////////////////////////////////////////////////////////////////////////////////////////
///additional event listener - rightclick to get back default zoom
google.maps.event.addListener(map, 'rightclick', function() {
map.setZoom(12);
map.setCenter(map.getPosition());
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CENTRING MAP AS ALL OF MARKERS IS VISIBLE//
//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < tablica.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(tablica[i][1], tablica[i][2]),
map: map
});
//extend the bounds to include each marker's position
bounds.extend(marker.position);
}
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
///SEARCH_BOX////////
///Here comes part of script adding search box
// Create the search box and link it to the UI element.
// Anchor search box and search button to the map.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
var button = document.getElementById('submitSearch');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(button);
//replacing polish characters on order to search without necessity typing them
function cleanUpSpecialChars(str)
{
str = str.replace(/[Ą]/g,"A");
str = str.replace(/[ą]/g,"a");
str = str.replace(/[Ę]/g,"E");
str = str.replace(/[ę]/g,"e");
str = str.replace(/[Ć]/g,"C");
str = str.replace(/[ć]/g,"c");
str = str.replace(/[Ł]/g,"L");
str = str.replace(/[ł]/g,"l");
str = str.replace(/[Ń]/g,"N");
str = str.replace(/[ń]/g,"n");
str = str.replace(/[Ó]/g,"O");
str = str.replace(/[ó]/g,"o");
str = str.replace(/[Ś]/g,"S");
str = str.replace(/[ś]/g,"s");
str = str.replace(/[Ź]/g,"Z");
str = str.replace(/[ź]/g,"z");
str = str.replace(/[Ż]/g,"Z");
str = str.replace(/[ż]/g,"z");
return str;
}
//Function, that search in array of markers, one which fits the key word written in searchbox.
$('#submitSearch').click(function() {
//Catching searched word and preparing its value for search process
var toSearch = $(input).val().trim();
toSearch = cleanUpSpecialChars(toSearch);
toSearch = toSearch.toLowerCase();
console.log('Szukana fraza -> ' + toSearch);
var results = [];
if (toSearch.length >=3) {
// Iterate through the array
$.each(markers, function (i, marker) {
//preparing certain elemnts of marker objects for search process
markers[i].title = cleanUpSpecialChars(markers[i].title);
markers[i].adress = cleanUpSpecialChars(markers[i].adress);
markers[i].title = markers[i].title.toLowerCase();
markers[i].adress = markers[i].adress.toLowerCase();
if (markers[i].title.indexOf(toSearch) > -1 || markers[i].adress.indexOf(toSearch) > -1) {
results.push(markers[i]);
}
});
if (results.length < 1) {
console.log ('nic');
$('#message2').slideDown(500, function () {
setTimeout(function () {
$('#message2').slideUp(500);
}, 5000);
});
}
// Close all the infoWindows, before rendering Search results.
markers.forEach(function (marker) {
marker.info.close(map, marker);
});
//Opens infWindows for multiple markers found and set bounds so that all markers found are visible
results.forEach(function (result) {
result.info.open(map, result);
bounds.extend(result.position);
});
map.fitBounds(bounds);
}
else{
//what if user has typed less than three characters in searchbox -> render flash mess.
$("#message").slideDown(500, function(){
setTimeout(function(){
$("#message").slideUp(500);
},5000);
});
}
});
//Enabling key Enter for triggering a search action.
$(input).keypress(function(e){
if(e.which == 13){//Enter key pressed
$('#submitSearch').click();//Trigger search button click event
}
});
},
//////////////////////////////////////////////////////////////////////////////////////////
//obsługa błędu, jeśli nie zostanie wyświetlona mapa
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(ajaxOptions);
alert('Map is broken. Please try again later.')
}
});
});
It will not qork here because it doesn't contain data from php.
I'm currently trying to code a simple web-app prototype for one of my university projects. I'm fairly new to Javascript and I'm having some trouble.
I've created a map that drops a marker at the user's current location, and a marker at a fixed point. Here is the Javascript so far:
var map;
function load() {
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
navigator.geolocation.getCurrentPosition(displayOnMap);
}
var pin;
function displayOnMap(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var initialLocation = new google.maps.LatLng(latitude, longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
map: map,
position: initialLocation,
});
loadMarkers();
}
function loadMarkers() {
var xmlMarkersRequest = new XMLHttpRequest();
xmlMarkersRequest.onreadystatechange = function() {
if (xmlMarkersRequest.readyState === 4) {
var xml = xmlMarkersRequest.responseXML;
var markersArray = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markersArray.length; i++) {
var id = Number(markersArray[i].getAttribute("id"));
var latitude = markersArray[i].getAttribute("latitude");
var longitude = markersArray[i].getAttribute("longitude");
var point = new google.maps.LatLng(
parseFloat(latitude),
parseFloat(longitude));
var marker2 = new google.maps.Marker({
map: map,
position: point,
zIndex: id
});
}
}
}
xmlMarkersRequest.open('GET', 'markers.xml', false);
xmlMarkersRequest.send(null);
}
Everything here works exactly how I want it to.
I'm just not sure how to use computeDistanceBetween to return the distance between the user's initial location (initialLocation), and the location of the marker.
The marker information is stored in an XML file because originally I planned to add more than one. But my site only needs one marker, so it's not a problem if I have to write the fixed marker's information into the Javascript instead.
I hope this question makes sense!
You need to load the geometry library
http://maps.googleapis.com/maps/api/js?key=YOURKEY&libraries=geometry
The distance between two points is the length of the shortest path between them. This shortest path is called a geodesic. On a sphere all geodesics are segments of a great circle. To compute this distance, call computeDistanceBetween() passing it two LatLng objects.
Example:
var a = new google.maps.LatLng(0,0);
var b = new google.maps.LatLng(0,1);
var distance = google.maps.geometry.spherical.computeDistanceBetween(a,b);
distance will be the distance in meters.
I have an Open-layers map, and I want to add a marker with a mouse over event that displays a pop up. my code is doing this however the pop-up is displayed not on top of the icon that is "mouse overed".
Instead the popup is displayed at the far side of the screen and moves the map slightly. I have added a mouse move function that tell me where the cursor is on the screen and the mouse move event is giving the correct coordinates but the mouseover is giving me values that are almost zero.
I am very new to JavaScript and I completely lost as to what I have got wrong here. any help would be greatly appreciated
here is the javascript
map = new OpenLayers.Map("map");
//var layer= new OpenLayers.Layer.OSM();
layer = new OpenLayers.Layer.Google(
"Google Hybrid",
{type: google.maps.MapTypeId.HYBRID, numZoomLevels: 20});
layer.wrapDateLine=false;
map.addLayer(layer);
map.zoomTo(3);
var clat=45.003585;
var clon=6.120495;
var lonlat = new OpenLayers.LonLat(clon,clat).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
map.setCenter(lonlat,18);
markers = new OpenLayers.Layer.Markers("Cities");
map.addLayer(markers);
var location = new OpenLayers.LonLat(6.12053255092622,45.00374430489748).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',size,offset);
marker=new OpenLayers.Marker(location,icon.clone());
map.addControl(
new OpenLayers.Control.MousePosition(
{
prefix: '<a target="_blank" ' +
'href="http://spatialreference.org/ref/epsg/4326/">' +
'EPSG:4326</a> coordinates: ',
separator: ' | ',
numDigits: 2,
emptyString: 'Mouse is not over map.'
})
);
map.events.register("mousemove", map, function(e)
{
position = this.events.getMousePosition(e);
OpenLayers.Util.getElement("coords").innerHTML = position;
lonlat = map.getLonLatFromPixel(position).transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
OpenLayers.Util.getElement("coords_gps").innerHTML = "lat= " +lonlat.lat +" long= "+lonlat.lon;
});
//here add mouseover event
marker.events.register('mouseover', marker, function(ev) {
lonlat = map.getLonLatFromPixel(this.events.getMousePosition(ev));
console.log(this.events.getMousePosition(ev));//.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326")));
popup = new OpenLayers.Popup.FramedCloud("Popup",
lonlat,
null,
'<div>Hello World! Put your html here</div>',
null,
false);
map.addPopup(popup);
});
//here add mouseout event
marker.events.register('mouseout', marker, function(evt) {popup.hide();});
markers.addMarker(marker);
map.events.register("click",map, function (e){
// alert("here");
position = this.events.getMousePosition(e);
lonlat = map.getLonLatFromPixel(position).transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
$('#lat').val(lonlat.lat);
$('#lon').val(lonlat.lon);
});
After some advice on how to clear markers on googlemaps, I have a map which I would like to have only one marker showing (basically the last marker clicked). I would like the user to be able to change thier mind and click multiple times, but not have confusing map of previous clicks etc.
I have tried the map.clearOverlay(); function, but it seems to permantly clear the whole map.
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("googlemap"));
map.setCenter(new GLatLng(50.401515,-4.866943), 8);
GEvent.addListener(map,"click", function(overlay,latlng) {
if (latlng) {
var myHtml = "" + latlng ;
split=myHtml.indexOf(",");
x=Math.round(myHtml.slice(1,split)*1000000)/1000000;
y=Math.round(myHtml.slice(split+1,myHtml.length-1)*1000000)/1000000;
document.collector.latitude.value=x;
document.collector.longitude.value=y;
lat="<br />Latitude: " + x;
lon="<br />Longitude: " + y;
latlon=""+lat+lon;
//map.openInfoWindow(latlng, latlon);
map.clearOverlay();
map.addOverlay(new GMarker(latlng));
}
});
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
}
}
Untested, but should do what you want - note that the setLatLng method of GMarker was introduced in API version 2.88:
function initialize() {
if (GBrowserIsCompatible()) {
var marker;
function showNewMarker(latlng) {
marker = new GMarker(latlng);
map.addOverlay(marker);
showMarker = updateExistingMarker;
}
function updateExistingMarker(latlng) {
marker.setLatLng(latlng);
}
var showMarker = showNewMarker;
var map = new GMap2(document.getElementById("googlemap"));
map.setCenter(new GLatLng(50.401515,-4.866943), 8);
GEvent.addListener(map,"click", function(overlay,latlng) {
if (latlng) {
var myHtml = "" + latlng ;
split=myHtml.indexOf(",");
x=Math.round(myHtml.slice(1,split)*1000000)/1000000;
y=Math.round(myHtml.slice(split+1,myHtml.length-1)*1000000)/1000000;
document.collector.latitude.value=x;
document.collector.longitude.value=y;
lat="<br />Latitude: " + x;
lon="<br />Longitude: " + y;
latlon=""+lat+lon;
//map.openInfoWindow(latlng, latlon);
map.clearOverlay();
showMarker(latlng);
}
});
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
}
}
It works by using a variable, showMarker, containing a reference to a function. This starts out pointing to a function, showNewMarker, which creates a marker, adds it to the map, and then changes showMarker to point to the function updateExistingMarker, which simply uses setLatLng to move the marker to a new position. This means that, on subsequent clicks, the existing marker will be moved to the location of the click.
I'm not too great with javascript. Does anyone know how I can increase the number of markers displayed on Google Maps. I'm pulling about 300 locations from a MySQL database, but it's only plotting 50 or so.
Here's the code I'm using:
<script type="text/javascript">
//<![CDATA[
var iconBlue = new GIcon();
iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconBlue.iconSize = new GSize(12, 20);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);
var iconRed = new GIcon();
iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconRed.iconSize = new GSize(12, 20);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["city"] = iconBlue;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(47.614495, -122.341861), 1);
map.setMapType(G_SATELLITE_MAP);
GDownloadUrl("map-xml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("geolocation");
for (var i = 0; i < markers.length; i++) {
var time = markers[i].getAttribute("time");
var date = markers[i].getAttribute("date");
var city = markers[i].getAttribute("city");
var type = markers[i].getAttribute("city");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, time, date, city, type);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, time, date, city, type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>Time:" + time + "<br />Date:" + date + "<br/>City:" + city +"</b>";
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//]]>
Thanks
I think you are looking for a Marker Manager.
I suspect that your markers are being plotted, but you're not seeing them for some reason.
Check that you're not plotting lots of markers at exactly the same location. If you plot one marker exactly on top of another it looks like one marker rather than of two.
Check that all your customIcons have image files in the right place. If there's no icon image you might not see anything.
customIcons[type] can fail if your "type" variable doesn't match one of your values. In particular the values are case specific. But if that's your problem you'd expect a Javascript error. Have you checked your error console?
Check that all your customIcons have a sensible size. If you omit the size parameter, the API will plot the image with zero size in some browsers.
I don't know of any limit on the markers allowed, I worked on a page with nearly 300 (http://bic-church.org/about/churches/map.asp). Mine, however, are loaded from a JSON file. Is it possible that you are experiencing some sort of timeout issue?
Edit: Additional thought: If you notice it consistently failing at a certain point, check the integrity of the data for that marker. You might find it is a bad lat/long or something.