My assignment asks to place multiple markers on the map based on an xml document that we need to parse. I've done the parsing, but I'm having from trouble figuring out how to put the lat and long elements into the new marker object. My code:
function loadPoint(){
// var newHTML= "<div style=\"padding:5px;border:solid 1px red\">";
// new_lat = escapeText($(this).find("latitude").number();
// new_long = escapeText($(this).find("longitude"));
// newHTML += new_lat + "," + new_long;
// newHTML += "</div>";
// $("body").append(newHTML);
var latlong= new google.maps.LatLng($(this).find("latitude"),$(this).find("longitude"));
var marker = new google.maps.Marker({
map: map,
position: latlong
})
}
function parser(data) {
$(data).find("item title").each(loadDescription);
$(data).find("item latitude").each(loadLat);
$(data).find("item longitude").each(loadLong);
$(data).find("item").each(loadPoint);
}
function myBadLoadFunction(myXMLHttpRequest,myErrorMessage,myErrorThrown) {
alert('status: ' + myErrorMessage + '\n' + myXMLHttpRequest.responseText);
}
var map;
var centerPoint = new google.maps.LatLng(53.608803,-1.497327);
function initializeMap(){
var myOptions = {
zoom: 8,
center: centerPoint,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map_canvas').get(0), myOptions);
In my head this makes sense...putting the parsed data as the params for creating a new latlng, but it does nothing so..
Try arranging your declarations first.
var map; //declare it here
function initialize(){
var centerPoint = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: centerPoint
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
}
function loadPoint(){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locations = [
[-33.890542, 151.274856],
[-33.923036, 151.259052],
[-34.028249, 151.157507],
[-33.80010128657071, 151.28747820854187],
[-33.950198, 151.259302]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
Related
I'm using the Google Maps API to capture the zoom level when the user clicks on the map. I would then like to increase the zoom level by 1, but I'm having trouble doing this and I'm getting multiple console.log entries when I run this in the browser.
Here's the script in question:
var map = null;
function initialize() {
var myOptions = {
zoom: 12,
scaleControl: true,
streetViewControl: false,
center: new google.maps.LatLng(-28.8413400, 153.4384050),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-28.8413400, 153.4384050),
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/blue.png',
title: ''
});
var point = new google.maps.LatLng(-27.7028557, 153.0120736);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 2</p>', icon)
var point = new google.maps.LatLng(-29.8089498, 152.8230076);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 4</p>', icon)
var point = new google.maps.LatLng(-26.6564235, 153.0586826);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 4</p>', icon)
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(100, 20)
});
function createMarker(latlng, html, icon) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: icon,
map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoomLevel = map.getZoom();
console.log(zoomLevel);
});
google.maps.event.addListener(map, "click", function(event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
var newCentre = latitude + ', ' + longitude;
var currentZoomLevel = map.getZoom();
console.log("currentZoomLevel: " + currentZoomLevel);
var zoomLevel = parseInt(currentZoomLevel, 10) + 1;
console.log("zoomLevel: " + zoomLevel);
});
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Markers</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.33&key=myKeyHere"></script>
<style type="text/css">
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map-canvas"></div>
</body>
</html>
When I look at the console log I can see multiple entries of the following:
[Log] currentZoomLevel: 12
[Log] zoomLevel: 13
It looks like it's generating an entry for each marker that I have on the map. For example if I have 3 markers I'm getting 6 entries in the console.log, but I'm not sure why this is happening?
Simply move your map event listeners outside of your createMarker function.
I also modified:
declared infowindow as a global variable so that it can be accessed in both functions
merged the 2 map click event listeners into one
var map = null;
var infowindow;
function initialize() {
var myOptions = {
zoom: 12,
scaleControl: true,
streetViewControl: false,
center: new google.maps.LatLng(-28.8413400, 153.4384050),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
myOptions);
infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(100, 20)
});
google.maps.event.addListener(map, 'click', function(event) {
infowindow.close();
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
var newCentre = latitude + ', ' + longitude;
var currentZoomLevel = map.getZoom();
console.log("currentZoomLevel: " + currentZoomLevel);
var zoomLevel = parseInt(currentZoomLevel, 10) + 1;
console.log("zoomLevel: " + zoomLevel);
});
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoomLevel = map.getZoom();
console.log(zoomLevel);
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-28.8413400, 153.4384050),
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/blue.png',
title: ''
});
var point = new google.maps.LatLng(-27.7028557, 153.0120736);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 2</p>', icon)
var point = new google.maps.LatLng(-29.8089498, 152.8230076);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 4</p>', icon)
var point = new google.maps.LatLng(-26.6564235, 153.0586826);
var icon = 'https://maps.google.com/mapfiles/ms/icons/red.png';
var marker = createMarker(point, '<p style="font-size:14px">Acme Services 4</p>', icon)
}
function createMarker(latlng, html, icon) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: icon,
map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
initialize();
#map-canvas {
height: 200px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
I use geolocation and I can view map my coordinates. Then, marker put the coordinate.
I want to change marker position.
My code here:
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
lat=position.coords.latitude;
lon=position.coords.longitude;
latlon=new google.maps.LatLng(lat, lon)
mapholder=document.getElementById('mapholder')
mapholder.style.height='250px';
mapholder.style.width='100%';
var myOptions={
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
};
var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);
var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
This code get my location coordinates. How can i change marker position?
I am sorry Eren about the my previous answer.I misunderstood.I think , this is correct one what you needed.
Display latitude and longitude on marker movement
Refer this site
I found a solution in this page. My problem is solved with this.
refer this
and this site
var map;
var myCenter = new google.maps.LatLng(37, 35);
var markersArray = [];
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
function initialize() {
var mapProp = {
center: myCenter,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
clearOverlays();
var marker = new google.maps.Marker({
position: location,
map: map,
});
markersArray.push(marker);
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
moveBus() is getting called before initialize(). Try putting that line at the end of your initialize() function. Also Lat/Lon 0,0 is off the map (it's coordinates, not pixels), so you can't see it when it moves. Try 54,54. If you want the center of the map to move to the new location, use panTo().
Demo: http: //jsfiddle.net/ThinkingStiff/Rsp22/
HTML:
<script src = "http://maps.googleapis.com/maps/api/js?sensor=false" > </script> <div id = "map-canvas"> </div>
CSS:
#map-canvas {
height: 400 px;
width: 500 px;
}
Script:
function initialize() {
var myLatLng = new google.maps.LatLng(50, 50),
myOptions = {
zoom: 4,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
marker.setMap(map);
moveBus(map, marker);
}
function moveBus(map, marker) {
marker.setPosition(new google.maps.LatLng(0, 0));
map.panTo(new google.maps.LatLng(0, 0));
};
initialize();
I have just started working with the Google Maps API, and am trying to display multiple markers across an array of data.
However I am getting a marker for just the first location in my list, which I guess means my loop isn't working properly, but I am not getting any errors to work from.
var mapOptions = {
center: centralLatlng,
zoom: 2
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var cdnLocations = [
['LondonMarker', 51.500, 0.1167],
['NewYorkMarker', 40.7127, -74.0059],
['TokyoMarker', 35.6895, 139.6917],
['BerlinMarker', 52.5167, 13.3833],
['ParisMarker', 48.8567, 2.3508],
['MadridMarker', 40.4000, 3.6833],
]
for (var i = 0; i < cdnLocations.length; i++) {
var cdnLocations = cdnLocations [i]
var marker = new google.maps.Marker({
position: new google.maps.LatLng (cdnLocations[1], cdnLocations[2]),
map: map,
});
}
Check this out:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locations = [
['LondonMarker', 51.500, 0.1167],
['NewYorkMarker', 40.7127, -74.0059],
['TokyoMarker', 35.6895, 139.6917],
['BerlinMarker', 52.5167, 13.3833],
['ParisMarker', 48.8567, 2.3508],
['MadridMarker', 40.4000, 3.6833],
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 1,
center: new google.maps.LatLng(35.68, 139.69),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
Here a jsfiddle example:
http://jsfiddle.net/m2htynto/
I am using the below javascript code to show map and marker.The marker is loading while map load,but i want to load the marker if the button named "Add marker" is clicked.The marker should points to the current location.How to do this here.
js.
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(-29.3456, 151.4346);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Marker',
map: map,
draggable: true
});
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
html
<div id="mapCanvas"></div>
Thanks
please try this. hope it help.
1. make map as global variable.
2. initialize map
3. add marker on button click event.
<script type="text/javascript">
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
};
jQuery("$addmarker").click(function(){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(23.72, 72.100),
title: 'Marker',
map: map,
draggable: true
});
})
</script>
Here is my complete sample code.
<script type="text/javascript">
var map;
function initialize()
{
var mapOptions = {
center: new google.maps.LatLng('23.11', '71.00'),
zoom: 2,
scrollwheel: false,
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
}
function addMarker()
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(23.72, 72.100),
map: map,
});
}
</script>
</HEAD>
<BODY onload="initialize();">
<div id="map_canvas" style="width:700px; height:500px;"></div>
<input type="button" id="addMarker" value="addMarker" onclick="addMarker();"/>
</BODY>
</HTML>
data is array which contains lat and lng
function addMarker(data) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map
});
You need to put the part:
var marker = new google.maps.Marker({
[...]
});
inside a onclick event listener.
The jQuery way to do this with a button element:
$('button').on('click', function() {
var marker = new google.maps.Marker({
[...]
});
});
You have to think about making the variables map and latLng global.
var map; // Declare map as global.
function initialize() {
var latLng = new google.maps.LatLng(-29.3456, 151.4346);
map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
// Call addMarker on click of the button.
function addMarker(){
var latLng = new google.maps.LatLng(-29.3456, 151.4346); // Put lat long as desired.
var marker = new google.maps.Marker({
position: latLng,
title: 'Marker',
map: map,
draggable: true
});
}
I wrote the following code to display markers. There are 2 buttons which show Next or Previous Infowindow for markers. But problem is that InfoWindows are not shown using google.maps.event.trigger
Can someone help me with this problem. Thank you.
Here is code:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Common Loader</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var infowindow;
var map;
var bounds;
var markers = [];
var markerIndex=0;
function initialize() {
var myLatlng = new google.maps.LatLng(41.051407, 28.991134);
var myOptions = {
zoom: 5,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
markers = document.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(markers[i].getAttribute("name"), latlng, markers[i].getAttribute("phone"), markers[i].getAttribute("distance"));
}
rebound(map);
}
function createMarker(name, latlng, phone, distance) {
var marker = new google.maps.Marker({position: latlng, map: map});
var myHtml = "<table style='width:100%;'><tr><td><b>" + name + "</b></td></tr><tr><td>" + phone + "</td></tr><tr><td align='right'>" + distance + "</td></tr></table>";
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: myHtml});
infowindow.open(map, marker);
});
return marker;
}
function rebound(mymap){
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng"))));
}
mymap.fitBounds(bounds);
}
function showNextInfo()
{
if(markerIndex<markers.length-1)
markerIndex++;
else
markerIndex = 0 ;
alert(markers[markerIndex].getAttribute('name'));
google.maps.event.trigger(markers[markerIndex],"click");
}
function showPrevInfo()
{
if(markerIndex>0)
markerIndex--;
else
markerIndex = markers.length-1 ;
google.maps.event.trigger(markers[markerIndex],'click');
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:400px; height:300px"></div>
<markers>
<marker name='Name1' lat='41.051407' lng='28.991134' phone='+902121234561' distance=''/>
<marker name='Name2' lat='40.858746' lng='29.121666' phone='+902121234562' distance=''/>
<marker name='Name3' lat='41.014604' lng='28.972256' phone='+902121234562' distance=''/>
<marker name='Name4' lat='41.012386' lng='26.978350' phone='+902121234562' distance=''/>
</markers>
<input type="button" onclick="showPrevInfo()" value="prev"> <input type="button" onclick="showNextInfo()" value="next">
</body>
</html>
this is how i'm doing it
hope it can help ;)
/**
* map
*/
var myLatlng = new google.maps.LatLng(39.980278, 4.049835);
var myOptions = {
zoom: 10,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
}
var map = new google.maps.Map(document.getElementById('mapa'), myOptions);
var infoWindow = new google.maps.InfoWindow();
var markerBounds = new google.maps.LatLngBounds();
var markerArray = [];
function makeMarker(options){
var pushPin = new google.maps.Marker({map:map});
pushPin.setOptions(options);
google.maps.event.addListener(pushPin, 'click', function(){
infoWindow.setOptions(options);
infoWindow.open(map, pushPin);
});
markerArray.push(pushPin);
return pushPin;
}
google.maps.event.addListener(map, 'click', function(){
infoWindow.close();
});
function openMarker(i){
google.maps.event.trigger(markerArray[i],'click');
};
/**
*markers
*/
makeMarker({
position: new google.maps.LatLng(39.943962, 3.891220),
title: 'Title',
content: '<div><h1>Lorem ipsum</h1>Lorem ipsum dolor sit amet<div>'
});
openMarker(0);
This code doesn't work because it is triggering click event on markers[markerIndex] which is not map marker but information about DOM element with tag marker.
To get it running you have to add global array which will contain list of map markers:
var markerList = [];
Change initialize() function to push map marker to that list in for loop:
markerList.push(marker);
Change functions showNextInfo() and showPrevInfo() to trigger event on map marker:
//google.maps.event.trigger(markers[markerIndex], "click");
google.maps.event.trigger(markerList[markerIndex], "click");