map don't display with googlemaps js API - javascript

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.

Related

Google Maps API: Create function that loads markers, so that it can be called with setInterval to update position of XML

I've created a file that loads markers into a Google Maps JavaScript API canvas.
The markers are generated from an XML file, which get's the markers info from SQL.
I want to be able to call a function ex. loadMarkers() so that I can update the markers position when the SQL data has changed.
As of now, I could call load() again, but then it refreshes the whole map, and not just the markers. Just like a hard refresh of the site..
How can I wrap the code for just inserting markers, so that I can call it back as a function?
<!DOCTYPE html >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script type="text/javascript">
var customIcons = {
user: {
icon: 'http://maps.google.com/mapfiles/kml/shapes/man.png'
},
store: {
icon: 'http://maps.google.com/mapfiles/kml/shapes/grocery.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(59.914045, 10.756808),
zoom: 12,
mapTypeId: 'roadmap',
mapTypeControl: false,
streetViewControl: false,
zoomControl: false,
fullscreenControl: false
});
// here I want a function that pushes the markers by calling ex. setMarkers() function, that can be called later by setInterval(function() {setMarkers();},3000) to update markers location if the xml is changed
downloadUrl("xml.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("name");
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>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
draggable: false,
animation: google.maps.Animation.DROP,
});
} // for each markers
}); //download url
} // load();
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() {}
**//This is the function I want to update the markers with, without having to do a hard refresh of the site.**
setInterval(function() {setMarkers();},3000);
</script>
</head>
<body onload="load()">
<div id="map"></div>
</body>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<?php echo $api_key; ?>&callback=initMap">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js sensor=false"></script>
</html>
create a function (setMarkers) that does the downloadUrl call to load the XML and create markers on the map.
make the map variable global or pass it in to that function
create a global array to track those markers so you can remove them before loading the new ones.
var gmarkers = [];
function setMarkers() {
downloadUrl(urlString, function(data) {
var xml = data.responseXML;
for (var i=0; i<gmarkers.length; i++)
gmarkers[i].setMap(null);
gmarkers = [];
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
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>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
draggable: false,
animation: google.maps.Animation.DROP,
});
gmarkers.push(marker);
} // for each markers
}); //download url
}
call that function in the load function and in the setTimeout.
var map;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(59.914045, 10.756808),
zoom: 12,
mapTypeId: 'roadmap',
mapTypeControl: false,
streetViewControl: false,
zoomControl: false,
fullscreenControl: false
});
setMarkers();
} // load();
setInterval(function() {
setMarkers();
},3000);
working example

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>

Passing latitude and longitude as parameters in url

I am trying to create an html file to show google maps. Here is the code I am using to accomplish it.
<!DOCTYPE html>
<html>
<head>
<title> Map</title>
</head>
<body>
<div id="map-container" class="col-md-6"></div>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
function init_map() {
var var_location = new google.maps.LatLng(12.989802,80.2487);
var var_mapoptions = {
center: var_location,
zoom: 14
};
var var_marker = new google.maps.Marker({
position: var_location,
map: var_map,
title:"Venice"});
var var_map = new google.maps.Map(document.getElementById("map-container"),
var_mapoptions);
var_marker.setMap(var_map);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
</body>
In this code the values and latitude and longitude are manually given inside the js. But i want that latitude and longitude to be passed as url parameters.
EX : http://www.smart.com/3.html?q=12.989802,80.2487
This is because my url will be called from an app and they want to pass latitude and longitude as a parameters.
You can write code to read and parse the query string. One description of how to do that is Part 20 Passing and receiving parameters of Mike Williams' Google Maps Javascript API v2 tutorial (note that v2 is deprecated and turned off, but the same principles apply to v3).
example using "q=40.7127837,-74.0059413" (the code snippet doesn't take query parameters)
function init_map() {
var lat, lng;
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?q=42,-72"
// 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).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "q") {
var coords = value.split(",");
lat = parseFloat(coords[0]);
lng = parseFloat(coords[1]);
}
}
var var_location;
if (isNaN(lat) || isNaN(lng)) {
var_location = new google.maps.LatLng(12.989802, 80.2487);
} else {
var_location = new google.maps.LatLng(lat, lng);
}
var var_mapoptions = {
center: var_location,
zoom: 14
};
var var_marker = new google.maps.Marker({
position: var_location,
map: var_map,
title: "Venice"
});
var var_map = new google.maps.Map(document.getElementById("map-container"),
var_mapoptions);
var_marker.setMap(var_map);
}
google.maps.event.addDomListener(window, 'load', init_map);
html,
body,
#map-container {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-container" class="col-md-6"></div>
I edited your function. Try this.
function init_map() {
var urlParams = /\?q=([^,]+),([^,]+)/.exec(window.location.search),
var_location;
if (urlParams) {
var_location = new google.maps.LatLng(parseFloat(urlParams[1]), parseFloat(urlParams[2]));
} else {
return;
}
var var_mapoptions = {
center: var_location,
zoom: 14
};
var var_marker = new google.maps.Marker({
position: var_location,
map: var_map,
title: "Venice"
});
var var_map = new google.maps.Map(document.getElementById("map-container"),
var_mapoptions);
var_marker.setMap(var_map);
}
Is this the behaviour you want? Just bear in the mind. If there are no required parameters in the url function will do nothing. Make sure to put any default or doing anything else. Good luck in implementation.

Google MAPS API V3 with icon types and select function

I am in the process of migrating my Google API v2 maps to version 3.
I have partially completed this successfully - see below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1- strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<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: Loading the data from an XML</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="downloadxml.js"></script>
<style type="text/css">
html, body { height: 100%; }
</style>
<script type="text/javascript">
//<![CDATA[
// this variable will collect the html which will eventually be placed in the select
var select_html = "";
// arrays to hold copies of the markers
// because the function closure trick doesnt work there
var gmarkers = [];
// global "map" variable
var map = null;
var image = {
url: 'ghd.png',
// This marker is 20 pixels wide by 32 pixels tall.
size: new google.maps.Size(59, 70),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
anchor: new google.maps.Point(0, 70)
};
var shadow = {
url: 'images/beachflag_shadow.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
size: new google.maps.Size(37, 32),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(0, 32)
};
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: shadow,
icon: image,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// ======= Add the entry to the select box =====
select_html += '<option> ' + name + '<\/option>';
// ==========================================================
// save the info we need to use later
gmarkers.push(marker);
return marker;
}
// ======= This function handles selections from the select box ====
// === If the dummy entry is selected, the info window is closed ==
function handleSelected(opt) {
var i = opt.selectedIndex - 1;
if (i > -1) {
google.maps.event.trigger(gmarkers[i],"click");
}
else {
infowindow.close();
}
}
function initialize() {
// create the map
var myOptions = {
zoom: 2,
center: new google.maps.LatLng(32.8624,-96.654218),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from 100.xml
downloadUrl("MW_100.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
// ==== first part of the select box ===
select_html = '<select onChange="handleSelected(this)">' +
'<option selected> - Select a location - <\/option>';
// =====================================
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point,label,html);
}
// ===== final part of the select box =====
select_html += '<\/select>';
document.getElementById("selection").innerHTML = select_html;
});}
var infowindow = new google.maps.InfoWindow(
{ size: new google.maps.Size(150,50)});
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
// from the v2 tutorial page at:
// http://econym.org.uk/gmap/basic3.htm
//]]>
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<!-- you can use tables or divs for the overall layout -->
<div id="map_canvas" style="width: 700px; height: 450px"></div>
<!-- ====== this div will hold the select box ==== -->
<div id="selection"></div>
<!-- ============================================= -->
<noscript><p><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.</p>
</noscript>
</body>
</html>
How ever, I want to introduce different types for the icon, and have this sub categorisation of icontypes as a field within the xml data. So I tried adjusting code to following, but does not output. Html/js below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtm
/DTD/xhtml1- strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<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: Loading the data from an XML</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="downloadxml.js"></script>
<style type="text/css">
html, body { height: 100%; }
</style>
<script type="text/javascript">
//<![CDATA[
// this variable will collect the html which will eventually be placed in the select
var select_html = "";
// arrays to hold copies of the markers
// because the function closure trick doesnt work there
var gmarkers = [];
var gicons = [];
var icon = new GIcon();
icon.iconSize = new GSize(46, 44);
icon.iconAnchor = new GPoint(23, 44);
icon.infoWindowAnchor = new GPoint(23, 7);
icon.shadowSize = new GSize(22, 20);
icon.shadowAnchor = new GPoint(100, 60);
gicons["yellow"] = new GIcon(icon, "ghd_grey.png");
gicons["grey"] = new GIcon(icon, "ghd2.png");
// global "map" variable
var map = null;
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html, icontype) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
gicons:icontype,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// ======= Add the entry to the select box =====
select_html += '<option> ' + name + '<\/option>';
// ==========================================================
// save the info we need to use later
gmarkers.push(marker);
return marker;
}
// ======= This function handles selections from the select box ====
// === If the dummy entry is selected, the info window is closed ==
function handleSelected(opt) {
var i = opt.selectedIndex - 1;
if (i > -1) {
google.maps.event.trigger(gmarkers[i],"click");
}
else {
infowindow.close();
}
}
function initialize() {
// create the map
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(43.907787,-79.359741),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from 100.xml
downloadUrl("MW_100.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
// ==== first part of the select box ===
select_html = '<select onChange="handleSelected(this)">' +
'<option selected> - Select a location - <\/option>';
// =====================================
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
var icontype = markers[i].getAttribute("icontype");
// create the marker
var marker = createMarker(point,label,html,icontype);
}
// ===== final part of the select box =====
select_html += '<\/select>';
document.getElementById("selection").innerHTML = select_html;
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
// from the v2 tutorial page at:
// http://econym.org.uk/gmap/basic3.htm
//]]>
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<!-- you can use tables or divs for the overall layout -->
<div id="map_canvas" style="width: 550px; height: 450px"></div>
<!-- ====== this div will hold the select box ==== -->
<div id="selection"></div>
<!-- ============================================= -->
<noscript><p><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.</p>
</noscript>
</body>
</html>
Sample xml:
label="Marker 2" icontype="yellow" />
You only need
var gicons=[];
gicons['yellow'] ="ghd_grey.png";
gicons["grey"] = "ghd2.png";
...
and in createMarker :
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon : gicons[icontype],
...
optimized: false, //important, else zIndex might not work
zIndex : 10 //google.maps.Marker.MAX_ZINDEX downto 0.
//use marker.setZIndex() to set it dynamically
...
});

Google Maps API showing blank map

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()">

Categories

Resources