Marker is not showing up on google map - javascript

I am trying to show markers on google map in a web page.
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
window.MY = {};
function test() {
addMarker(new google.maps.LatLng(88.4, 22.5));
}
function addMarker(myLatlng) {
var marker = new google.maps.Marker({
position: myLatlng,
map: MY.map
});
}
function initialize() {
var myOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
MY.map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
navigator.geolocation.getCurrentPosition(function(position) {
MY.map.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
});
google.maps.event.addListener(MY.map, 'click', function(event) {
addMarker(event.latLng);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="height:380px;"></div>
<button onclick="test()">test</button>
</body>
</html>
When I click on the map, marker shows up, but when I click on test button, marker doesn't show up for the specified location(88.4, 22.5). Can someone please explain me the behavior.

The location google.maps.LatLng(88.4,22.5) is above the arctic circle. A latitude of 88.4 is very close to the north pole.
Perhaps you want google.maps.LatLng(22.5,-88.4) (in the Gulf of Mexico) or google.maps.LatLng(22.5,88.4) (Kolkata, India).

Replace your function test with
function test() {
var position = new google.maps.LatLng(88.4, 22.5)
addMarker(position);
MY.map.setCenter(position);
}
Your marker is falling outside map's viewport.

Related

Google Map API marker update from JS

I would like to ask you a solution for this problem.
I have a JS with a variable inside that is updated overtime by a JAVA application (i.e. JAVA writer into a thread), after that I take the coordinates from that variable and I create a new object Marker for my google maps. The problem is that the marker does not changes position, it changes only if I refresh the whole page (I dont want to do this).
Here's the code to be more clear.
The inputData.js where the variable is written by the java application
var newMarker = {'latitude':38.25705300000004,'longitude': 140.83760400000006};
my html page used to display the map
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEY">
</script>
<script type="text/javascript" src="inputData.js"></script>
<script>
var map;
var sendai = new google.maps.LatLng(38.259535, 140.846816);
var lastPosition;
var image = 'images/circle-16.png';
function initialize() {
var mapOptions = {
zoom: 12,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
setInterval(refreshData, 2000);
function refreshData() {
var marker = new google.maps.Marker({
map: map,
icon: image,
draggable: false
});
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
If I open my page like this everything work but when I change the script "inputData.js" the marker does not changes position.
The method setCenter on the other hand seems to work properly.
Help me please!
You'll need to reload the updated script to get the updated position:
function initialize() {
var mapOptions = {
zoom: 18,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP},
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions),
//we will store the LatLng here
pos = new google.maps.MVCObject(),
//use a single marker with updated position
marker = new google.maps.Marker();
//set the latLng of the MVCObject
pos.set('latLng',new google.maps.LatLng(newMarker.latitude,
newMarker.longitude));
//bind the markers position to the latLng of the MVCObject
marker.bindTo('position',pos,'latLng');
marker.setMap(map);
setInterval(function(){
//the currently loaded script
var script=document.querySelector('script[src^="inputData.js"]'),
//the updated script
update=document.createElement('script');
//load-handler for the updated script
google.maps.event.addDomListenerOnce(update,'load',function(){
pos.set('latLng',new google.maps.LatLng(newMarker.latitude,
newMarker.longitude));
map.setCenter(pos.get('latLng'));
map.setZoom(18);
});
//replace current script with updated script
script.parentNode.replaceChild(update,script);
//load update
update.src='inputData.js?'+new Date().getTime();
},2000);
}
You don't need to create new instance of marker every time. Update your code with this and try:
var map;
var sendai = new google.maps.LatLng(38.259535, 140.846816);
var lastPosition;
var image = 'images/circle-16.png';
function initialize() {
var mapOptions = {
zoom: 12,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
var marker;
marker = new google.maps.Marker({
map: map,
icon: image,
draggable: false
});
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
setInterval(refreshData, 2000);
function refreshData() {
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
}
google.maps.event.addDomListener(window, 'load', initialize);

How to add marker to the googlemaps in a web page

This is my entire code(just a test page). It shows the map but not the marker. How can I make it show the marker?
<!DOCTYPE html>
<html>
<head>
<style>
#map_canvas {
width: 500px;
height: 400px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
The problem with your code is that you haven't defined any variable latLng and you are using it in marker. So obviously your code will not work. First define the latLng and then use.
Define it something like this:
var latLng = new google.maps.LatLng(44.5403, -78.5463);//Your marker coordinates.
and then use it in your code like:
var marker = new google.maps.Marker({
position: latLng,
map: map
});
Demo : http://jsfiddle.net/lotusgodkk/x8dSP/3520/

Click on the google map to open a link in a new window

I used the code from a website as shown below to let me show a google map in my page.
You can see it in action here http://www.pcpro.co.uk/blogs/wp-content/uploads/2010/12/google-maps-simple-example.html
My question is how can i change the code to when a user clicks on the map to open a link in a new window?
Thank you
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
$(document).ready(function () {
// Define the latitude and longitude positions
var latitude = parseFloat("38.1447817");
var longitude = parseFloat("23.848843");
var latlngPos = new google.maps.LatLng(latitude, longitude);
// Set up options for the Google map
var myOptions = {
zoom: 15,
center: latlngPos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Define the map
map = new google.maps.Map(document.getElementById("map"), myOptions);
// Add the marker
var marker = new google.maps.Marker({
position: latlngPos,
map: map,
title: "Auto Marin"
});
});
</script>
<div id="map" style="width:230px;height:140px;"></div>
You could add an event listener.
google.maps.event.addListener(map, "click", function(){
window.open(*LINK*)
});

Google Maps v3 Listener (click) - Change URL

I have a Google Maps map with a markercluster, and various points. Generating the points like below with the event listener, it goes off for every single point on page load.
function mappyfuntime() {
var mapOptions = {
center: new google.maps.LatLng(51.481581,-3.17909),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("bigmap"), mapOptions);
<?php echo prepare_javascript(); ?>
var markers = [];
var marker = [];
linkto = new Array();
for(g=0; g<LocationsArray.length; g++) {
var latlng = new google.maps.LatLng(LocationsArray[g][0], LocationsArray[g][1]);
marker[g] = new google.maps.Marker({'position': latlng});
markers.push(marker[g]);
google.maps.event.addListener(marker[g], 'click', click_handler(PermalinksArray[g]));
}
var markerCluster = new MarkerClusterer(map, markers);
}
mappyfuntime();
function click_handler(link) {
alert(link);
}
However, if I change the google.maps.event.addListener to the following, the alert comes back undefined.
google.maps.event.addListener(marker[g], 'click', function() {
alert(PermalinksArray[g]);
});
And if I pass PermalinksArray[g] to the function, the same thing happens. Is there any way to get a piece of information from an array (which is globally defined) when its corresponding point is clicked on the map?
I guess the Permalinks Array comes from the php insert? Well then its not in global scope. Try puttung that php-insert at the top of your javascript script.
// set globals
var map;
var markers = [];
var PermalinksArray = ['...'];
var LocationsArray = ['...'];
function mappyfuntime() {
// init map
var mapOptions = {
center: new google.maps.LatLng(51.481581,-3.17909),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("bigmap"), mapOptions);
// create markers
for(g=0; g<LocationsArray.length; g++) {
// create new Position
var latlng = new google.maps.LatLng(LocationsArray[g][0], LocationsArray[g][1]);
// create new marker with position
var marker = new google.maps.Marker({'position': latlng});
// add event to marker
google.maps.event.addListener(marker, 'click', function() {
click_handler(marker, PermalinksArray[g]);
});
// push marker into markers array
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
}
function click_handler(marker, link) {
alert(link);
}
mappyfuntime();
I have created a Google Map with 2 markers and when a marker is clicked then the area's name appears in the info window. The information in the markers is loaded through a global defined array named cityList. You can find my code below.
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps - Google maps jQuery plugin</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"> </script>
<script type="text/javascript">
var cityList = [
['Chicago', 41.850033, -87.6500523, 1],
['Illinois', 40.797177,-89.406738, 2]
],
demoCenter = new google.maps.LatLng(41,-87),
map;
function initialize()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: demoCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function addMarkers()
{
var marker, i;
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < cityList.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(cityList[i][1], cityList[i][2]),
map: map,
title: cityList[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(cityList[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
$(document).on("pageinit", "#basic-map", function() {
initialize();
});
$(document).on('click', '.add-markers', function(e) {
e.preventDefault();
addMarkers();
});
</script>
</head>
<body>
<div id="basic-map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
<a data-rel="back">Back</a>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
Add Some More Markers
</div>
</div>
</body>
</html>
I hope this helps.

Google Maps API V3 not rendering competely on tabbed page using Twitter's Bootstrap

I'm using Twitter's Bootstrap for defining my CSS. I have made a page with three tabs. The second tab contains a map built with Google Maps. However when opening the page and switching to the second page with the map, the map is not rendered completely. Once I reload the page with the google maps tab as the selected tab the map loads entirely.
I read some posts that advised people with the same problem to add the following code to the javascript:
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
However this doesn't seem to be the solution. Please find the complete code below:
Javascript:
<script type="text/javascript">
function initialize() {
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("data.xml", function(data) {
var markers = data.documentElement.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 = new google.maps.Marker({position: latlng, map: map});
}
});
}
</script>
HTML:
<div class="tab-pane" id="orange" style="background-color:#E3F2FF;">
<div id="map_canvas" style="width:780px; height:400px; overflow:;"></div>
</div>
How can I resolve this? Maybe I can add some javascript that reloads the google maps part once the tab is selected but I don't know how to do this....
Updated code still shows the error:
<div class="tab-pane" id="orange" style="background-color:#E3F2FF;">
<div id="map_canvas" style="width:780px; height:400px; overflow:;"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="util.js"></script>
<script type="text/javascript">
function initialize() {
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("data.xml", function(data) {
var markers = data.documentElement.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 = new google.maps.Marker({position: latlng, map: map});
}
});
map.checkResize();
}
</script>
</div>
I was battling with this issue as well. I was using a modal form and it rendered the map when it was hidden. When the tab is shown, you need to trigger this code:
google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );
Hopefully it will work for you. If that doesn't work, here is the link where I found the solution. Maybe there will be another helpful comment.
http://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
There's a lot of solutions here and frankly they're all wrong. If you have to hi-jack the default functionality of Bootstrap tabs, you might as well not use Bootstrap tabs. If you're only calling resize after the tab is shown, you may still have issues with the GMaps interface (zoom level and such). You simply have to initialize the map after the tab is visible.
var myCenter=new google.maps.LatLng(53, -1.33);
var marker=new google.maps.Marker({
position:myCenter
});
function initialize() {
var mapProp = {
center:myCenter,
zoom: 14,
draggable: false,
scrollwheel: false,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
};
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
initialize();
});
You can see a working example in this bootply: http://www.bootply.com/102241
Note: if your interface is still glitchy, it could be this issue:
Google Maps API V3 : weird UI display glitches (with screenshot)
Using the most recent gmaps api, you just need to add this to your styling:
.gm-style img { max-width: none; }
.gm-style label { width: auto; display: inline; }
Works for me after testing different delays :
$(window).resize(function() {
setTimeout(function() {
google.maps.event.trigger(map, 'resize');
}, 300)
});
Hope it helps.
I have solved the problem by using
google.maps.event.trigger(map, 'resize');
inside show function in bootstrap-tab.js means at the time of showing the box you should trigger resize event and will work..
Edit: I have seen another link with the same answer
Google Maps API v3, jQuery UI Tabs, map not resizing
I have seen this link after solving the problem to find out the reason which is still unanswered that why resize event does not works on the click event of the tabs but works in the tab js
this works fine for me, I use jquery tabs
setTimeout(function() {
google.maps.event.trigger(map, "resize");
map.setCenter(new google.maps.LatLng(default_lat, default_lng));
map.setZoom(default_map_zoom);
}, 2000);
from this link https://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
To show a google maps in a hidden div, the div must show before the map is created and loaded. Below is an example:
<div id="map_canvas" style="width:500px; height:500px"></div>
<script>
$(document).ready(function(){
$('#button').click(function() {
$('#map_canvas').delay('700').fadeIn();
setTimeout(loadScript,1000);
});
});
function initialize() {
var title= "Title";
var lat = 50;
var lng = 50;
var myLatlng = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:artTitle
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
For me, what it worked was to call the function that renders the map after the, in my case, the modal had shown.
All I had to do was:
$(document).on("shown", "#eventModal", function(){
bindMap(coordinates);
});
You can do the same with the tabs, because they also have a "shown" event.

Categories

Resources