Google Maps API showing blank map - javascript

I'm sure this is a basic problem but I've hit my head against the wall too many times now, so hopefully someone will take pity on me!
I have the following example but all it does is show a grayed out box, no map at all. Can anyone tell me why?
I've checked that I'm actually returning a result and it seems to be working fine.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html, body, #map-canvas {margin: 0;padding: 0;height: 100%;}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize()
{
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "England"}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(results[0].geometry.location),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Let's draw the map
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
initialize();
</script>
</head>
<body onload="">
<div id="map-canvas" style="width: 320px; height: 480px;"></div>
</body>
</html>

Try resizing the browser window, give a shake to browser/drag it from browser tab with the cursor and you will see the map appearing.
From some strange reason in MVC partial view google map comes as blank, your map is working it just need to be resized.
Shaking a browser window with cursor sounds funny, but it works and I am not sure how to best describe it.
Thanks,
Anurag
=======================================================================
my final working code is below:
`
<script type="text/javascript">
$(document).ready(function () {
(function () {
var options = {
zoom: 6,
center: new google.maps.LatLng(-2.633333, 37.233334),
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: false
};
// init map
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
var arrLocation = [];
$("#markerDiv").find("div").each(function () {
var Lat = $(this).find("input[id='Latitude']").val();
var Lon = $(this).find("input[id='Longitude']").val();
var Id = $(this).find("input[id='Id']").val();
var AssessmentDet = $(this).find("input[id='AssessmentDateTime']").val();
var LocAcc = $(this).find("input[id='LocationAccuracy']").val();
var assessorName = $(this).find("input[id='AssessorName']").val();
var partnerName = $(this).find("input[id='PartnerName']").val();
arrLocation.push({
Id: Id,
Latitude: Lat,
Longitude: Lon,
AssessmentDate: AssessmentDet,
LocationAccuracy: LocAcc,
AssessorDetail: assessorName,
PartnerName: partnerName
});
});
var allMarkers = [];
for (var i = 0; i < arrLocation.length; i++) {
//final position for marker, could be updated if another marker already exists in same position
var latlng = new google.maps.LatLng(arrLocation[i].Latitude, arrLocation[i].Longitude);
var finalLatLng = latlng;
var comparelatlng = "(" + arrLocation[i].Latitude + "," + arrLocation[i].Longitude + ")";
var copyMarker = arrLocation[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(arrLocation[i].Latitude, arrLocation[i].Longitude),
map: map,
title: 'Equine # ' + arrLocation[i].Id,
icon:"abc.png"
});
var markerInfo = "Reference # : <b>" + arrLocation[i].Id + "</b><br/>";
markerInfo = markerInfo + "Assessor : <b>" + arrLocation[i].AssessorDetail + "</b><br/>";
markerInfo = markerInfo + "Date : <b>" + arrLocation[i].AssessmentDate + "</b><br/>";
markerInfo = markerInfo + "Partner : <b>" + arrLocation[i].PartnerName + "</b>";(function (marker, i) {
bindInfoWindow(marker, map, new google.maps.InfoWindow(), markerInfo);
})(marker, i);
}
})();
});
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
</script>
`

results[0].geometry.location is already a latLng object so you can just say:
center: results[0].geometry.location
Find the working fiddle here : http://jsfiddle.net/87z9K/

It is because of the worng "google.maps.LatLng" provided.
provide for a test the coords and it will work.
replace the line
center: new google.maps.LatLng(results[0].geometry.location),
with
center: new google.maps.LatLng(-34.397, 150.644)
get England coords

It wasn't exactly your issue, but closely related.
I found that I had to set the mapOptions with a valid centre, like so:
new google.maps.Map(mapCanvas, {
center: new google.maps.LatLng(-34.397, 150.644)
});
If I didn't enter map options, or if I did and it didn't have a valid center set, I'd get a blank map that didn't load tiles.

This can also occur if the height/width of the map is 0.

I tried to set map's MapTypeId and it helped as Anurag proposed:
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);

I can see a general javascript issue with your code.
Your script might trying to embed the map in the page before the HTML is loaded.
Call the function like this (there are other ways).
<body onload="initialize()">

Related

Google maps toggle kml and json layer

Im working with the Google maps API.
I am loading a KML file and a JSON file with jQuery.
The KML file is bike routes in Toronto and the JSON files shows markers for where the Bike Share stations are in Toronto.
When both are loaded, the bike routes don't show up... I think this is because the two files are too big (but but by themselves they load up fine).
Anyway, I would like to load the page with the JSON file, then have a button that when clicked removes the markers and loads the KML file. Another button would remove the KML file and load the markers.
I can't find a way to do this.
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDr2ZlJyFHjsjjItTPK7_bvRiw_YBchXW4">
</script><link rel="stylesheet" type="text/css" href="http://www.richardbeardwood.com/stylesassign3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(43.663112,-79.403468),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
$.getJSON("http://api.citybik.es/bixi-toronto.json", function(json1) {
var infoWindow = new google.maps.InfoWindow();
$.each(json1, function(key, data) {
var lat = data.lat;
var newLat = lat.toString().match(/.{2}/g).join('.');
var nextLat = newLat.split('.');
var finLat = nextLat.shift() + '.' + nextLat.join('');
var lng = data.lng;
var newLng = lng.toString().match(/.{3}/g).join('.');
var nextLng = newLng.split('.');
var finLng = nextLng.shift() + '.' + nextLng.join('');
var latLng = new google.maps.LatLng(finLat, finLng);
// Creating a marker and putting it on the map
//var imagebike = 'http://www.richardbeardwood.com/bikes_maps_marker.png';
var marker = new google.maps.Marker({
position: latLng,
icon: 'http://maps.google.com/mapfiles/kml/pal3/icon53.png'
});
var bikeLayer = new google.maps.KmlLayer({
url: 'http://www.richardbeardwood.com/TorontoCyclingMap.kml.xml'
});
bikeLayer.setMap(map);
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
var gettime = new Date(data.timestamp);
var time = gettime.toString();
infoWindow.setContent('<div id="iw-container"><div class="iw-title">' + data.name + '</div><div class="iw-content"><p><img src="http://www.richardbeardwood.com/Bicyle-Symbolgreen.jpg" height="115" width="114"></p><p> As of ' + time + ' at this location there are:<br><br><strong><span class="large">Available docks: ' + data.free + '<br><br>Available bikes: ' + data.bikes + '</span></strong></div></div>');
infoWindow.open(map, marker);
});
marker.setMap(map);
});
});
}
</script>
<script>
function clearMarkers() {
bikeLayer.setMap(null);
}
</script>
</head>

Autozoom / Autocenter with GoogleMaps Avi v3 JS

I'm writing a code in order to display some pushpins on a maps, using Google Maps V3 APi (JS).
I would like to use Autozoom and Autocenter.
For this, i need to use Bound.extends() and map.fitBounds(), nevertheless, with the use of this functions i have only one pushpins...not the other...it's very strange...
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap">
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 768px"></div>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
// A function to create the marker and set up the event window
function createMarker(point,name)
{
var marker = new google.maps.Marker({position: point, title: name});
google.maps.event.addListener(marker, "click", function(){
marker.openInfoWindowHtml(name);});
return marker;
}
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'));//, { center: {lat: -34.397, lng: 150.644},zoom: 8});
var geocoder = new google.maps.Geocoder();
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), optionsCarte);
var bounds = new google.maps.LatLngBounds();
// ========== Read paramaters that have been passed in ==========
// If there are any parameters at the end of the URL, they will be in location.search
// looking something like "?q=My+First+Point#59.591,17.82"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++)
{
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1);
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "q")
{
var text = unescape(value);
var parts = text.split("#");
geocoder.geocode( { 'address': parts[1]}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);//center the map over the result
var title = parts[0];
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
bounds.extend(results[0].geometry.location);
}
}
map.fitBounds(bounds)
map.panToBounds(bounds);
map.setCenter(bounds.getCenter());
}
</script>
In order to execute my call, i have to do this :
http://XX.XX.XX.XX/MutliMaps.html?q=MyPushPin1#myAdresse1&q=MyPushPin2#myAdresse2
Any idea where is my error? I think it's the bound.extend fonction.
You must move the code related to the bound, zoom and center inside the loop
so you first you have geocode result available (and so you don't get the error for this ) and second you can extend the bound incrementally ..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap">
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 768px"></div>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
// A function to create the marker and set up the event window
function createMarker(point,name)
{
var marker = new google.maps.Marker({position: point, title: name});
google.maps.event.addListener(marker, "click", function(){
marker.openInfoWindowHtml(name);});
return marker;
}
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'));//, { center: {lat: -34.397, lng: 150.644},zoom: 8});
var geocoder = new google.maps.Geocoder();
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), optionsCarte);
var bounds = new google.maps.LatLngBounds();
// ========== Read paramaters that have been passed in ==========
// If there are any parameters at the end of the URL, they will be in location.search
// looking something like "?q=My+First+Point#59.591,17.82"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++)
{
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1);
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "q")
{
var text = unescape(value);
var parts = text.split("#");
geocoder.geocode( { 'address': parts[1]}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);//center the map over the result
var title = parts[0];
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location});
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds)
map.panToBounds(bounds);
map.setCenter(bounds.getCenter());
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
//bounds.extend(results[0].geometry.location);
}
}
//map.fitBounds(bounds)
///map.panToBounds(bounds);
//map.setCenter(bounds.getCenter());
}
</script>

map don't display with googlemaps js API

I'm tryin to use a sample code in order to have a webpage in order to display multiples pushpin on the map.
Here is my html code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap">
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 768px"></div>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
// A function to create the marker and set up the event window
function createMarker(point,name)
{
var marker = new google.maps.Marker({position: point, title: name});
google.maps.event.addListener(marker, "click", function(){
marker.openInfoWindowHtml(name);});
return marker;
}
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'));//, { center: {lat: -34.397, lng: 150.644},zoom: 8});
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), optionsCarte);
var bounds = new google.maps.LatLngBounds();
// ========== Read paramaters that have been passed in ==========
// If there are any parameters at the end of the URL, they will be in location.search
// looking something like "?q=My+First+Point#59.591,17.82"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++)
{
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1);
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "q")
{
var text = unescape(value);
var parts = text.split("#");
var latlng = parts[1].split(",");
var point = new google.maps.LatLng(parseFloat(latlng[0]),parseFloat(latlng[1]));
var title = parts[0];
var marker = createMarker(point,title);
marker.setMap(map);
bounds.extend(point);
}
}
//map.setZoom(map.getBoundsZoomLevel(bounds));
map.fitBounds(bounds)
map.setCenter(bounds.getCenter());
}
</script>
The trick is to use the url with parameters in order to add locations to display :
Ex: http://myserver.com?q=MyFirstPoint#59.591,17.82
Actually nothing is displayed..
Anyone can help me please ? My API key is on the code ;)
Thanks a lot,
Best regards,
Fab'
You have a
callback=initMap
but I see no function by this name
and similar you have
<body onunload="GUnload()">
but I see no function by this name
You must be suure you call the proper init function for display the maps and check in browser console for other errors
?q=MyFirstPoint#59.591,17.82&q=MyLastPoint#54.591,12.82
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="map" style="width: 550px; height: 450px"></div>
<script>
(function (myGoogleMap) {
var map;
var latLngBounds;
myGoogleMap.init = function () {
console.log('init');
latLngBounds = new google.maps.LatLngBounds();
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8,
mapTypeId: google.maps.MapTypeId.TERRAIN,
panControl: false,
zoomControl: true,
mapTypeControl: true,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false
});
getData();
};
function getData() {
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i = 0, l = pairs.length; i < l; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0, pos).toLowerCase();
var value = pairs[i].substring(pos + 1);
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "q") {
var text = decodeURI(value);
var parts = text.split("#");
var latlng = parts[1].split(",");
setMarker(parseFloat(latlng[0]), parseFloat(latlng[1]), parts[0]);
}
}
centerMap();
}
function setMarker(lat, lng, contentString) {
var latLng = new google.maps.LatLng(lat, lng);
latLngBounds.extend(latLng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
}
function centerMap() {
map.fitBounds(latLngBounds);
}
}(window.myGoogleMap = {}))
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=myGoogleMap.init"></script>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
</body>
</html>
I hope this could help.

Auto filled search box

I have this code which shows a marker from my current location and sets the coordinates into the page title, buy now I want to add a search box for adresses but I need that the text of the search box changes to the corresponding coordinates when the markes is draged. and i have no idea hot to do that
here is my code
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map_canvas{
height:800px;
width:800px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=true">
</script>
<script>
navigator.geolocation.getCurrentPosition(initialize);
var marker, map;
function initialize(position ) {
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 14,
center: coords,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
window.document.title= new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mark = new google.maps.Marker({
position: coords ,
map: map,
draggable:true
});
google.maps.event.addListener(mark, 'dragend', function(evt){
window.document.title = evt.latLng.lat() + ',' + evt.latLng.lng() ;
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Test this, and tell me what you think of it
I used the document.getElementById() to select the search_box, and changed its innerHTML.
I slightly modified your event listener
google.maps.event.addListener(mark, 'dragend', function(evt){
var coordinates = {lat: evt.latLng.lat(), lng: evt.latLng.lng()};
window.document.title = coordinates.lat + ',' + coordinates.lng ;
document.getElementById('search_box').innerHTML = coordinates.lat + ',' + coordinates.lng ;
});
and I added a div with an id of search_box in your HTML.

Multiple Locations Google map

How can i show multiple locations on google map.
I am using this code for google map?
<script type="text/javascript">
$(function() { // when the document is ready to be manipulated.
if (GBrowserIsCompatible()) { // if the browser is compatible with Google Map's
var map = document.getElementById("myMap"); // Get div element
var m = new GMap2(map); // new instance of the GMap2 class and pass in our div location.
var longArray= ("<?php echo $long; ?>").split(',');
var latArray= ("<?php echo $lat; ?>").split(',');
for(i=0;i<longArray.length;i++)
{
m.setCenter(new GLatLng(latArray[i], longArray[i]), 13); // pass in latitude, longitude, and zoom level.
m.openInfoWindow(m.getCenter(), document.createTextNode("This is testing")); // displays the text
}
m.setMapType(G_SATELLITE_MAP); // sets the default mode. G_NORMAL_MAP, G_HYBRID_MAP
var c = new GMapTypeControl(); // switch map modes
m.addControl(c);
m.addControl(new GLargeMapControl()); // creates the zoom feature
}
else {
alert("Upgrade your browser, man!");
}
});
</script>
Refer below code, that worked perfectly fine for me.
The code snippet below will give you an error to provide valid API key i.e. "Google Maps JavaScript API error: InvalidKeyMapError", to resolve this the only thing you need is valid API Key provided by google maps.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Multiple Locations using Google Maps </title>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false"></script>
</head>
<body>
<div id="googleMap" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locationArray = [
['Pune', 18.5248904, 73.7228789, 1],
['Mumbai', 19.0825223, 72.7410977, 2],
['Ahmednagar', 19.1104918, 74.6728675, 3],
['Surat', 21.1594627, 77.3507354, 4],
['Indore', 22.7242284, 75.7237617, 5]
];
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 8,
center: new google.maps.LatLng(18.5248904,73.7228789),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locationArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationArray[i][1], locationArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locationArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
For more details refer here. I hope this is what you are looking for!
setCenter is used to zoom and center the map.. if you want to mark multiple locations you need to create a marker and place it on the map inside your loop.. there's a good set of tutorials here:
http://econym.org.uk/gmap/index.htm
If your question relates to showing multiople disparate locations on a single map then you cant, a map can only be centered on one lat/lng at a time..
Its not entirely clear what you're trying to achieve.
Dunc.
following steps you have to follow.
1. make a list of your addresses in javascript aaray.
2. make a utility function to geocode and then put marker by passing address as arguement.
3. iterate over your addresses array and call your marker utility function.
example: map.jsp ::
it tales input json string that is list of addresses and the converts it to javascript array:
add the jquery and infobox.js by downloading fron google.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# page contentType="text/html;charset=windows-1252"%>
<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>
<script language="JavaScript" src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
<script language="JavaScript" src="js/infobox.js" type="text/javascript"></script>
</head>
<body>
<%
String json=request.getParameter("address");
%>
<input type="hidden" id="json" value="<%=json%>"></input>
<div id="map" style="width: 1250px; height: 500px;" align="center"></div>
<script type="text/javascript" language="JavaScript" src="js/map.js"></script>
<script type="text/javascript">
var jsonvalue=document.getElementById("json").value;
var use=unescape(jsonvalue);
//alert(use);
var obj = eval ("(" + use + ")");
var cobj=obj.center;
var olist=obj.other;
codeproject(cobj.center_add,cobj.center_name);
//alert(cobj.center_name+" and "+cobj.center_add);
for(var i=0;i<olist.length;i++)
{
//alert(olist[i].other_add);
codeAddress(olist[i].other_add,olist[i].other_name);
}
</script>
</body>
</html>
________map.js________
//used by infowindow
//the googlemap code
var geocoder = new google.maps.Geocoder();
//var infowindow = new google.maps.InfoWindow();
var LatLngList = new Array(6);
var i;
var infowindow = new google.maps.InfoWindow();
var markerBounds = new google.maps.LatLngBounds();
var markerarray=new Array();
//making the div for window popup
var boxText = document.createElement("div");
boxText.style.cssText = "border: 2px solid Gray; margin-top: 6px; background: white; padding: 5px;font-weight: bold;color: Gray;";
boxText.innerHTML = " ";
//options array for infobox window
var myOptions = {
map:map,
content : boxText,
disableAutoPan : false,
maxWidth : 0,
pixelOffset : new google.maps.Size( - 140, 0),
zIndex : null,
boxStyle : { background : "url('tipbox.gif') no-repeat", width : "280px" },
closeBoxMargin : "10px 4px 2px 2px", closeBoxURL : "close.gif",
infoBoxClearance : new google.maps.Size(1, 1),
isHidden : false,
pane : "floatPane",
enableEventPropagation : true
};
var infoBox;
function codeproject(address, client) {
geocoder.geocode( {
'address' : address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker( {
map : map, icon : 'green-dot.png', position : results [0].geometry.location, draggable : false, animation : google.maps.Animation.DROP
});
//bounce the marker
// marker.setAnimation(google.maps.Animation.BOUNCE);
//initialize info box
infoBox = new InfoBox(myOptions);
markerBounds.extend(results[0].geometry.location);
//listeners
google.maps.event.addListener(marker, 'mouseover', function () {
//stop bouncing
// marker.setAnimation(null);
// $("img[src$='iws3.png']").hide();
// infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address);
// infowindow.open(map, this);
boxText.innerHTML = "<br>"+client +"<br>"+results[0].formatted_address;
infoBox.setContent(boxText,marker);
infoBox.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function () {
// infowindow.close();
infoBox.close();
//start bounce
// marker.setAnimation(google.maps.Animation.BOUNCE);
});
//ok end
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
alert("Error Occured during geocode:" + status);
}
// alert('Geocode was not successful for '+client +' the following reason: ' + status);
}
});
}
function codeAddress(address, client) {
// var address = document.getElementById('address').value;
geocoder.geocode( {
'address' : address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
infoBox = new InfoBox(myOptions);
var marker = new google.maps.Marker( {
map : map,
// icon : 'smallpin.png',
position : results[0].geometry.location, draggable : false, animation : google.maps.Animation.DROP
});
//make bounds
//bounce the marker
// marker.setAnimation(google.maps.Animation.BOUNCE);
//initialize info box
markerBounds.extend(results[0].geometry.location);
//listeners
google.maps.event.addListener(marker, 'mouseover', function () {
//stop bouncing
// marker.setAnimation(null);
$("img[src$='iws3.png']").hide();
// infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address + '<\br>');
//infowindow.open(map, this);
boxText.innerHTML = "<br>"+client +"<br>"+results[0].formatted_address ;
infoBox.setContent(boxText,marker);
infoBox.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function () {
// infowindow.close();
//start bounce
infoBox.close();
// marker.setAnimation(google.maps.Animation.BOUNCE);
});
//ok end
}
else {
// alert('Geocode was not successful for '+client +' the following reason: ' + status);
}
});
}
//////////////calling the above two functions
var centerpoint = new google.maps.LatLng(43.652527, - 79.381961);//for ontario canada zoom level-7
//map intializing
var map = new google.maps.Map(document.getElementById('map'),
{
zoom : 4, backgroundColor : '#B5B5B5', draggable : true, center : centerpoint, mapTypeId : google.maps.MapTypeId.ROADMAP
});
///geocoding multiple addresses
//bounce markers
function toggleBounce(mark) {
if (mark.getAnimation() != null) {
mark.setAnimation(null);
}
else {
mark.setAnimation(google.maps.Animation.BOUNCE);
}
}
/////
function putmarker(address,client,lat,lng) {
var position = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker( {
map : map, icon : 'green-dot.png', position : position, draggable : false, animation : google.maps.Animation.DROP
});
//bounce the marker
// marker.setAnimation(google.maps.Animation.BOUNCE);
//initialize info box
infoBox = new InfoBox(myOptions);
markerBounds.extend(position);
//listeners
google.maps.event.addListener(marker, 'mouseover', function () {
//stop bouncing
// marker.setAnimation(null);
// $("img[src$='iws3.png']").hide();
// infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address);
// infowindow.open(map, this);
boxText.innerHTML = "<br>"+client +"<br>"+address;
infoBox.setContent(boxText,marker);
infoBox.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function () {
// infowindow.close();
infoBox.close();
//start bounce
// marker.setAnimation(google.maps.Animation.BOUNCE);
});
//ok end
}

Categories

Resources