I'm in the process of updating my google maps code to version 3 and i've come across a problem.
In version 2, I was reading in an xml file to create a marker and I was centering my map based on the coordinates, but in version 3 the center has been defined in the map variable before the xml file has been read.
Is this easy to fix?
Version 3 code taken from http://code.google.com/apis/maps/articles/phpsqlajax_v3.html
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("results.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("event");
var address = markers[i].getAttribute("location");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
Maybe you mean map.setCenter(latlng:LatLng) ?Parse your xml, create the markers,then center the map where you want.
Related
First thing is I will tell you I am new to google maps and some of it is very confusing to me. What I need to do is show a users location and have the appropriate markers show up. I have the database all ready and somewhat of the Google map.
What I am working with is an example from here. What I can either get is the markers if I use a static LatLng or just the users dynamic location with no markers.
Need help please. And if you downvote this post please let me know why.
Code I am using can be found at https://jsfiddle.net/8q1apmdy/9/ and show where in the blow code is where I am missing something, most likely small or in the wrong position.
function initMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
});
var map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 12
});
}
a) While running your code locally, I was getting 'pos' undefined, so I moved the following code 'var map = new google.maps.Map(..' inside the getCurrentPosition(){...
b) Then I got another error ' InvalidValueError: setMap: not an instance of Map;' so created a 'var map' globally.
Loaded the map successfully, but still markers were not loaded. while debugging your code at this point 'var marker = new google.maps.Marker({...' it is iterating for all markers from xml but somehow markers are not adding to the map..dont know the reason yet?
So I have tried in a different way. Please see all markers from xml displayed on map. Here I am just getting the 'name' in marker, you might need to add other parameters like id, address etc.
JSFiddle added for reference
var infowindow;
var map;
//var downloadUrl;
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-33.868820, 151.209290),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
downloadUrl("https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml", function(data) {
var bounds = new google.maps.LatLngBounds();
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute('id');
var address = markers[i].getAttribute('address');
var type = markers[i].getAttribute('type');
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
bounds.extend(latlng);
var marker = createMarker(id, markers[i].getAttribute("name"), address, latlng, type);
}//finish loop
//map.fitBounds(bounds);
}); //end downloadurl
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
}
function createMarker(id, name, address, latlng, type) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: name});
infowindow.open(map, marker);
});
return marker;
}
JSFiddle
I have written the following code to display markers and have respective info windows displaying name of the policestation.
The policestation class has name, latitude and longitude.
<script>
function initialize()
{
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var myCenter = new google.maps.LatLng(28.6523605,77.0910645);
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var mapProp = {
center: myCenter,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = [];
var info= [];
<%
ArrayList<PoliceStation> stationList = new PoliceStation().loadclass();
for (int i=0 ; i < stationList.size() ; i++) {
%>
var pos = new google.maps.LatLng(
<%= stationList.get(i).getLatitude()%>,
<%= stationList.get(i).getLongitude()%>
);
marker = new google.maps.Marker({
position: pos,
map: map
});
marker.setMap(map);
var MarkerContent = "<div class=\"marker\">" +
"<h2>"+ "<%=stationList.get(i).getstationName()%>"
+"</h2>"+
"</div>";
info=new google.maps.InfoWindow();
info.setOptions({
content: MarkerContent,
size: new google.maps.Size(50, 50),
position: pos
});
google.maps.event.addListener(marker, 'click', function () {
info.setOptions({
content: MarkerContent
});
info.open(map, marker);
});
<%
}
%>
All the markers are set as expected. However clicking any marker results in opening the infowindow of only the last marker drawn.
I get that this is because all the marker, infoWindow names are redundant and in the end only the last infoWindow gets saved to the last marker.
I have come across solutions that encapsulate the content inside the for loop with
(function() {var marker = ...; google.maps.event.addListener...;})();
However, I'm looking for a solution to dynamically distinctly define each variable name.
like for example append the value of a counter incremented at each iteration to each marker and info variable.
Kindly do not provide JSTP solution. looking for a specific JSP solution
Surprisingly it was really easy...
JSP is basically used to print HTML dynamically.
so, instead of using marker variable as
var marker = new google.maps.Marker({
position: pos,
map: map
});
use -
var <%out.print("marker"+i);%> = new google.maps.Marker({
position: pos,
map: map
});
It is to be noted that-
var <%out.print("marker["+i+"]");%> = new google.maps.Marker({
position: pos,
map: map
});
did not work for me.
The correct code above creates new variables with values marker1, marker2... etc
also the content update function inside the event listener-
info.setOptions({
content: MarkerContent
});
is not required.
I am working in a project to provide a map to mobile phone. For now I am trying on a iPhone.
It works fine, and when I load my first page I can see a map with my position, and the market is refreshed each 10 sec and move to my next position.
Some time when I change of page and I come back to the first page, the map is not full displayed. If I move the map, it move but some image of the map is still not displayed.
Also I am working with jquery mobe.
I also noticed that each time I return to the first map, the map is reloaded.
Is there a way to load the map once?
So how can i check that my map is already loaded?
Here is my code
$('#home').live('pagebeforeshow', function(e){
// Resize #mapHome (#mapHome = Sreen hight - footer - header)
$('#mapHome').css('height', Resize.content()-2 +'px');
// extract les id des modules existants
navigator.geolocation.getCurrentPosition(function(position){
showMap('mapHome',position.coords.latitude, position.coords.longitude);
//console.log(position.coords.latitude, position.coords.longitude);
},
function(){
//error
},
{
enableHighAccuracy : true,
maximumAge : 30000
//maximumAge:Infinity
});
// Place and move the marker regarding to my position and deplacement
var track_id = "me";
Tracking.watch_id = navigator.geolocation.watchPosition(
// Success
function(position){
console.log('WatchPosition called');
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latLng = new Array();
latLng[0] = lat;
latLng[1] = long;
//Tracking.myCoordinates.push(lat,long);
Tracking.myCoordinates.push(latLng);
addMarker(lat, long);
},
// Error
showError,
{
frequency: 1000
});
})
I just changed that line to
$('#home').live('pageshow', function(e){... code...}
And it semas to be better but I am not sure-
Here is the code of my function showMap()
function showMap(canvas,lat,long){
var latLng = new google.maps.LatLng(lat,long);
// Google Map options var myOptions = {
zoom: 19,
//zoomControl : 1,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP////ROADMAP, SATELLITE, HYBRID and TERRAIN };
// Create the Google Map, set options Tracking.mapy = new google.maps.Map(document.getElementById(canvas), myOptions);
}
And here is the code addMarker()
function addMarker(lat, long){
Tracking.mapBounds = new google.maps.LatLngBounds();
// Clean previous markers
for (var i = 0; i < Tracking.markers.length; i++ ) {
Tracking.markers[i].setMap(null);
}
// Add the owner's marker
var latitudeAndLongitude = new google.maps.LatLng(lat, long);
var image = "img/iconGoogleMap/phones.png";
marker = new google.maps.Marker({
title : 'me',
//animation: google.maps.Animation.DROP, //BOUNCE
position: latitudeAndLongitude,
map : Tracking.mapy,
icon : image
});
Tracking.markers.push(marker);
//Tracking.markers.push(marker);
//console.log(localStorage.getItem('mapToDisplay'));
/* ADDING MODULES MAKERS */
// Store the ID of available module.
modulesJSON = Modules.get('bipme');
for (var i = 0; i < modulesJSON['modules'].length; i++) {
console.log('module id = ' +modulesJSON['modules'][i].id);
console.log('Module ' + modulesJSON['modules'][i].id + ' position : ' + ModulesPos.module(modulesJSON['modules'][i].id));
nlatLong = ModulesPos.module(modulesJSON['modules'][i].id).split(",");
var LatitudeAndLongitudeModules = new google.maps.LatLng(nlatLong[0],nlatLong[1]);
var image = "img/iconGoogleMap/" + modulesJSON['modules'][i].profile + "-" + modulesJSON['modules'][i].iconColor + ".png";
marker = new google.maps.Marker({
title : modulesJSON['modules'][i].pseudo,
//animation: google.maps.Animation.DROP, //BOUNCE
position: LatitudeAndLongitudeModules,
map : Tracking.mapy,
icon : image
});
Tracking.mapBounds.extend(LatitudeAndLongitudeModules);
Tracking.markers.push(marker);
};
By the way, is there a way to create a button, from which I can manually refresh the map?
I'm trying to have custom infowindows float above markers, however I noticed that only one marker can be opened at any one time. Is there a workaround to this?
Here's the code I have produced at the moment:
downloadUrl("AllActivityxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("id");
var address = markers[i].getAttribute("id");
var type = markers[i].getAttribute("venue_type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng"))
);
var infowindow = new google.maps.InfoWindow();
var html = "<b>" + point + "</b>hello <br/>" + type;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
markersArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map,marker);
});
}
});
And when you check this map, notice that I cannot open more than 2 infowindows at once. Why is that?
There is no limitation implicit to the Google Maps API v3 that makes only one InfowWindow available at a time. You need to write your code to do that. If you want an InfoWindow for each marker, make one.
Some thing like (not tested):
function createMarker(latlng, html) {
var contentString = html;
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}
I do not know what to do... I just want to close all opened infoBubbles if I'm going to open a new one. I am using the following code. Ideas? I tried a lot and googled a lot but it shouldn't be so complicated, should it? I thought to create an array and save id for the open one, but I think that there must be another, quite easier way to fix this.
$(document).ready(function(){
createmap();
function createmap(lat,lng){
var latlng = new google.maps.LatLng(50, 10);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
bounds = new google.maps.LatLngBounds();
createMarker();
}
function createMarker(){
var markers = [];
var cm = window.cm = new ClusterManager(
map,
{
objClusterIcon: new google.maps.MarkerImage('images/map/flag_cluster.png', false, false, false, new google.maps.Size(20,20)),
objClusterImageSize: new google.maps.Size(20,20)
}
);
var json = [];
var x1 = -85;
var x2 = 85;
var y1 = -180;
var y2 = 180;
for (var i=0; i<20; ++i) {
json.push(
'{'+
'"longitude":'+(x1+(Math.random()*(x2-x1)))+','+
'"latitude":'+(y1+(Math.random()*(y2-y1)))+','+
'"title":"test"'+
'}'
);
}
json = '['+json.join()+']';
// eval is ok here.
eval('json = eval(json);');
infos = [];
$.each(json, function(i,item){
var contentString = '<div id="content"><a onclick="createdetailpage('+i+');">'+item.title+'<br /></a></div>';
console.log(item.latitude);
var myLatlng = new google.maps.LatLng(item.latitude,item.longitude);
var marker = new google.maps.Marker({
position: myLatlng,
//map: map,
flat: true,
title:item.title,
//animation: google.maps.Animation.DROP,
//icon: myIcon
});
var infoBubble = new InfoBubble({
content: '<div class="phoneytext">'+contentString+'</div>'
});
google.maps.event.addListener(marker, 'click', function() {
if (!infoBubble.isOpen()) {
infoBubble.open(map, marker);
}
});
cm.addMarker(marker, new google.maps.Size(50, 50));
});
map.fitBounds(bounds);
}
});
The simplest approach to only have one infoBubble open is to only have one infoBubble and open it with different contents depending on the marker that is clicked.
InfoWindow example with custom markers (same concept applies to InfoBubble)
The InfoBubble is an OverlayView. As far as I can see, an overlaycomplete event is emitted when an overlay is added. Maybe all your InfoBubbles could listen to that event and close if the added overlay is a different one than "this".
It's just a thought, though, I haven't tried it myself. Feedback appreciated if you try it out!