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>
Related
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.
I am displaying Map in my Application.I have added the code below and now the map is displaying correctly for particular city name. My Problem is i need to fetch location by using latitude and longitude of a particular city.
I don't want any new code. Is it possible the get the latitude and longitude values within this code itself by pass #item.Latitude#item.Longitude instead of #item.city
<div class="gMapsCanvas" data-address="#item.city"></div>
<script type="text/javascript">
var GoogleMap = function ga(canvas, address) {
// debugger;
var _parent = this;
//this.location = new google.maps.LatLng(-34.397, 150.644);
var options =
{
center: this.location,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions:
{
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_CENTER
},
streetViewControl: false
};
this.map = new google.maps.Map(canvas, options);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status != google.maps.GeocoderStatus.OK)
return;
_parent.location = results[0].geometry.location;
var marker = new google.maps.Marker(
{
map: _parent.map,
position: _parent.location
});
_parent.resize();
});
};
GoogleMap.prototype.resize = function () {
google.maps.event.trigger(this.map, "resize");
this.map.setCenter(this.location);
}
var Maps = function (classes) {
var _parent = this;
this.maps = new Array();
classes.each(function () {
_parent.maps.push(new GoogleMap($(this).get(0), $(this).attr("data-address")));
});
};
Maps.prototype.resize = function () {
for (var cnt = 0; cnt < this.maps.length; cnt++) {
this.maps[cnt].resize();
}
};
var maps;
</script>
<script type="text/javascript">
$(".tiptext").mouseover(function () {
$(this).children(".description").show();
maps = new Maps($(".gMapsCanvas"));
}).mouseout(function () {
$(this).children(".description").hide();
});
</script>
There are a number of different ways to display Google Maps in your browser.
but the two most easy and good ways are:
1. to Use Goggle MAP API https://developers.google.com/maps/?hl=en
2. Google Polymer as shown below:
<!-- Polyfill Web Components support for older browsers -->
<script src="components/webcomponentsjs/webcomponents-lite.min.js"></script>
<!-- Import element -->
<link rel="import" href="components/google-map/google-map.html">
<!-- Use element -->
<google-map latitude="37.790" longitude="-122.390"></google-map>
Try { 'latlng': latitude + ',' + longitude } instead of { 'address': address }.
I didn't test it but it seems to work according to googlemap webservice api : https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding
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
...
});
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()">
Hi i have create a web application in which i can show distance between two place on map using google V3 api and in other web application i have created animation drop marker which i can move on the map how can i combine these two. here is my code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Direction2.aspx.cs" Inherits="Direction2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var latlng = new google.maps.LatLng(51.764696, 5.526042);
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "My location"
});
}
function calcRoute() {
var start = document.getElementById("routeStart").value;
var end = "51.764696,5.526042";
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:710px; height:300px"></div>
<form action="" onsubmit="calcRoute();return false;" id="routeForm">
<input type="text" id="routeStart" value=""/>
<input type="submit" value="Route plannen"/>
<div id="directionsPanel"></div>
</form>
</body>
</html>
And for animation i use this code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Drop.aspx.cs" Inherits="Drop" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Drop</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var stockholm = new google.maps.LatLng(59.32522, 18.07002);
var parliament = new google.maps.LatLng(59.327383, 18.06747);
var marker;
var map;
function initialize() {
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: stockholm
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
position: parliament
});
google.maps.event.addListener(marker, 'click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
</script>
</head>
<body onload="initialize()" onunload="Gunload()">
<form id="form1" runat="server">
<div id="map_canvas" style="width:525px; height:237px;">
</div>
</form>
thanks in advance
To change the name of the start or destination city when you move the marker, you need to find the start and end coordinates of the directions and use googles geocoder to find the name of the locations.
You need to listen for the 'directions_changed' event and find the start and end latlngs.
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
var directions = this.getDirections();
var overview_path = directions.routes[0].overview_path;
var startingPoint = overview_path[0];
var destination = overview_path[overview_path.length - 1];
if (typeof startLatlng === 'undefined' || !startingPoint.equals(startLatlng)) {
startLatlng = startingPoint;
getLocationName(startingPoint, function(name) {
routeStart.value = name;
});
}
if (typeof endLatlng === 'undefined' || !destination.equals(endLatlng)) {
endLatlng = destination;
getLocationName(destination, function(name) {
routeEnd.value = name;
});
}
});
To get the name of the markers location use the following function (I put this together quickly, will need more testing)
function getLocationName(latlng, callback) {
geocoder.geocode({location: latlng}, function(result, status) {
if (status === google.maps.GeocoderStatus.OK) {
var i = -1;
// find the array index of the last object with the locality type
for (var c = 0; c < result.length; c++) {
for (var t = 0; t < result[c].types.length; t++) {
if (result[c].types[t].search('locality') > -1) {
i = c;
}
}
}
var locationName = result[i].address_components[0].long_name;
callback(locationName);
}
});
}
By doing it this way, you can't set a click event to the map markers applied to the map, which means you can't have your marker bouncing animation. If you need the marker animation, then you would have to suppress the markers in the directions service and display your own markers. When the marker is dragged you would have to recalculate the directions and then use the getLocationName function with the markers position.
Here is a working demo.
Should be enough to get you closer to what you want.
EDIT I've updated the code to change the value of the start or end input box when dragging.
The marker drag event will fire hundreds of times when only dragging a small distance, so we need to set a timer as not to request to many geocodes.
I've put together a working demo of this here: http://jsfiddle.net/SMEAD/6/
We needed to use our own markers so when initializing the DirectionsRenderer we need to pass in the suppressMarkers option
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
We only need to listen for directions changed once and set the markers.
google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
var directions = this.getDirections();
var overview_path = directions.routes[0].overview_path;
var startingPoint = overview_path[0];
var destination = overview_path[overview_path.length - 1];
addMarker(startingPoint, 'start');
addMarker(destination, 'end');
});
The work horse function is addMarker. This sets up the events we need to update the input boxes and recalculate the directions.
function addMarker(position, type) {
var marker = new google.maps.Marker({
position: position,
draggable: true,
animation: google.maps.Animation.DROP,
map: map
});
marker.type = type; // probably not a good idea to do this.
google.maps.event.addListener(marker, 'drag', function() {
var marker = this;
clearTimeout(dragTimer);
dragTimer = setTimeout(function() {
getLocationName(marker.getPosition(), function(name) {
if (marker.type === 'start') {
routeStart.value = name;
} else {
endStart.value = name;
}
});
}, 250);
});
google.maps.event.addListener(marker, 'dragend', function() {
calcRoute(startMarker.getPosition(), endMarker.getPosition());
});
if (type === 'start') {
startMarker = marker;
} else {
endMarker = marker;
}
}