Google Maps Autozoom - javascript

I have the following page, which by defaults opens a map centered on France:
http://www.villasdirect.com/_admin/dev/Country_MapV3.asp
It does seem to auto zoom to a certain extent, however when I look at France or Germany (just a couple of examples) the countries are not zoomed in close enough. If I search London however, it seems to be pretty much perfect - as in filling the box with a map of London.
You can see the different results here:
http://www.villasdirect.com/_admin/dev/Country_MapV3.asp?l=france
What I am aiming to do is the fill the map with the country, town or region, when selected... possible?
Help appreciated as always!
Here is my code too:
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
location = request.QueryString("l")
if location = "" then location = "France"
%>
<!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 type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<div id="map" style="width: 800px; height: 600px"></div>
<form onsubmit="showAddress(); return false" action="#">
<input id="search" size="60" type="hidden" value="<%=location%>" />
</form>
<div id="message"></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[
var xmlsource = '<markers><marker Town="Fayence" Region="Provence - Var" type="green" lng="6.694103" lat="43.624076"/><marker Town="La Cadiere d\'Azur" Region="Provence - Var" type="green" lng="5.755173" lat="43.196218"/><marker Town="Villefranche Du PĂ©rigord" Region="South West France" type="green" lng="1.080006" lat="44.62966"/><marker Town="Limetz-Villez" Region="Paris" type="green" lng="1.547366" lat="49.029137"/><marker Town="Boulogne-Billancourt" Region="Paris" type="green" lng="2.237803" lat="48.84325"/><marker Town="Saint-Germain-En-Laye" Region="Paris" type="green" lng="2.0934031" lat="48.8955155"/></markers>'
var myOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var infoWindow = new google.maps.InfoWindow;
$( $.parseXML( xmlsource ) ).find("marker").each(function() {
var lng = $(this).attr('lng');
var lat = $(this).attr('lat');
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(59.32522, 18.07002)
});
});
google.maps.event.addListener(marker, 'click');
// ====== Create a Client Geocoder ======
var geo = new google.maps.Geocoder();
geo.geocode({'address': document.getElementById("search").value}, function (results, status) {
var ne = results[0].geometry.viewport.getNorthEast();
var sw = results[0].geometry.viewport.getSouthWest();
map.fitBounds(results[0].geometry.viewport);
placeMarkers();
});
function placeMarkers(){
var xmlList = $.parseXML(xmlsource);
var markers = $(xmlList).find('marker');
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat($(markers[i]).attr("lat")),
parseFloat($(markers[i]).attr("lng")));
var type = $(markers[i]).attr("type");
var imgnam = "";
if(type == "green") {
imgnam = "http://openmbta.org/images/map/PinDown1Green.png?1306943843";
}else{
imgnam = "http://openmbta.org/images/map/PinDown1.png?1306943843";
}
var img = new google.maps.MarkerImage(
imgnam,
new google.maps.Size(30,35),
new google.maps.Point(0,0),
new google.maps.Point(15,35)
);
//add a link to your xml that can be inserted here where I have http://www.google.com
var html = "<a href='http://www.google.com'>" + $(markers[i]).attr('Region') + ', ' + $(markers[i]).attr('Town') + "</a>";
var marker = new google.maps.Marker({position: latlng, map: map, icon: img, html:html});
var infowindow1 = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow1.setContent(this.html);
infowindow1.open(map, this);
});
}
}
</script>
</body>
</html>

It's an old question but I think I have an answer. Instead of this:
map.fitBounds(results[0].geometry.viewport);
try this:
map.fitBounds(results[0].geometry.bounds);
According to Google Maps API documentation results.geometry.bounds may return a slightly different viewport. It's not exactly a solution, but it's worth a try.
Moreover, as I understand, Google Maps doesn't have imagery at infinite zoom levels and when fitBounds() is invoked, it will automatically select the highest zoom level that contains the given bounds and at which imagery is available. In your case, the bounds are the border of France and the viewport fits the border of France at the current zoom level. If you go just one zoom level further, the boundaries of France go out of the viewport.
You can change the size of viewport. For a certain size of viewport (I can't say exactly what size) you might achieve a perfect fit. You cited an example of London. I'm sure that for certain viewport sizes, London doesn't perfectly fit the viewport either. So, it's by chance that you came across a viewport size that is perfect for London.
If you still want more zoom, and can't change the viewport size, I suggest you try getZoom() then increment the result by 1 and setZoom(). Then again, that renders the border areas out of the viewport.
Cheerio!

Afaik there is no way of getting the information as to the physical dimensions of an area (be it city/county/country) from google.
If you had a database yourself with the sizes for every city/state/country combo then I guess you could do it with comparisons.
Otherwise, you're pretty much stuck with this one.

Related

Google Map images are really tiny inside infowindow

I've got a script working to add markers to a map with an infowindow. The problem is that the images are tiny, yet when you inspect and hover over the img entity the size is correct, and the blue box that shows where the canvas sits in the main window is correctly proportioned, it's just the actual image takes up a fraction of the canvas.
I've no idea on what is causing this. Using the Developer Tools I've removed all CSS that appears to be affecting it and nothing changes, except if I remove the 100% width, then the canvas goes full size, but the image is still only a fraction of the canvas.
This is the Javascript
var startLat = 20;
var startLng = 0;
var startZoom = 2;
var isAddress = false;
var distributors = [{"logo":"http:\/\/www.elecro.demomycms.co.uk\/eshop\/files\/images\/distributor-logos\/5.jpg","name":"AG Budget Swimming Pool & Spas","contactNumber":"020 89416618","address":"Unit 10 Wilden Industrial Estate\nWilden Lane\nStourport on Severn\nWorcestershire","postcode":"DY13 9JY","latitude":"52.3504","longitude":"-2.26002"}];
var map;
var geocoder;
$(function () {
var mapOptions = {
zoom: startZoom,
center: new google.maps.LatLng(startLat, startLng)
}
var marker, i;
$('#map-canvas').height($('#map-canvas').width() / 2);
var mapOptions = {
zoom: startZoom,
center: new google.maps.LatLng(startLat, startLng)
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if ( ! isAddress && $('#country').val() > 0) {
GeocodeCountry();
}
for (i = 0; i < distributors.length; i++) {
var $distributor = distributors[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng($distributor.latitude, $distributor.longitude),
map: map
});
var infowindow = new google.maps.InfoWindow();
marker.html = '<div class="container-fluid" style="width: 300px">\
<h1 class="row-fluid">\
'+($distributor.logo ? '<div class="span3"><img src="'+$distributor.logo+'" style="width: 100%"></div>' : '')+'\
<span class="span9">'+$distributor.name+'</span>\
</h1>\
<div class="row-fluid">\
<div class="span6">'+$distributor.address+'<br>'+$distributor.postcode+'</div>\
<div class="span6">'+($distributor.url ? ''+$distributor.url+'' : '')+'<br>'+$distributor.contactNumber+'</div>\
</div>\
</div>';
google.maps.event.addListener(marker, 'click', (function() {
return function() {
infowindow.setContent(this.html);
infowindow.open(map, this);
}
})(marker, i));
}
});
function GeocodeCountry() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': $('#country').find('option:selected').text()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
}
});
}
You have probably noticed the Bootstrap 2 code in the HTML, we're using Bootstrap 2 on the site, but I've not included any of the CSS / JS files in the fiddle below and it is still doing the same thing, so it's not Bootstrap affecting it.
You can see a JS fiddle of this here: http://jsfiddle.net/styphon/raLcmbvc/
I've only included one example marker in the JS Fiddle, but on the site there are over 200 and it does the same with all of them. This is the site if you want to see: http://elecro.demomycms.co.uk/distributors.php
Your testing image is huge, and also contains a lot of whitespace on right and bottom: http://www.elecro.demomycms.co.uk/eshop/files/images/distributor-logos/5.jpg
Then you also apply width:100% CSS to your image, so it will be resized to fit the window.
Depending on what you want to achieve, you could either:
User a better image without whitespace
Remove the width:100%
The problem here is that the image which your displaying is itself having large portion of itself as white!
See the link: http://www.elecro.demomycms.co.uk/eshop/files/images/distributor-logos/5.jpg and try saving the image and looking its dimensions. Its a huge 1433x755 size image of which almost 90% area is white background. So remove the extra white background by cropping the image and you be should be good to go. Rest everything seems fine. You can adjust image size in your code line <div class="container-fluid" style="width: 300px"> by giving appropriate width but first change the image.

Google maps v3 api Map doesnt fully load

I am building an app that will have maps showing nearby eateries.
Map shows up, but takes a very long time to load, and never actually fully loads.
I am on a deadline with this, and I've tried a variety of solutions with no luck.
Someone please help!!!
See code below:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Food & Drink</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<body>
<div id="map" style="width: 360px; height: 300px;"></div>
<script type="text/javascript">
var locations = [
['Little Shebas', 39.833691, -84.892375, 1],
['Roscoes Coffee Bar & Tap Room', 39.833891, -84.892130, 2],
['Ullerys Homemade Icecream', 39.834401, -84.889190, 3],
['Firehouse BBQ and Blues', 39.833630, -84.891887, 4],
['Tin Lizzie Cafe', 39.829140, -84.890857, 6]
['Joes Pizza', 39.834409, -84.889822, 5],
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 25,
center: new google.maps.LatLng(39.830184, -84.893401),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
I cannot confirm the behavior you described. Everything seems to be working fine and your code looks like it should work.
Check out this working example of your code. I played around with the inital zoom level and adjusted the center. The center you had specified wasn't really near the markers and the zoom level was so high at first I thought the map wasn't loading.
var center = new google.maps.LatLng(39.833691, -84.892375);
google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
I believe the problem in your array. Looking at the code in chrome dev tools it shows the locations array to contain 5 elements (not 6) the fifth of which is undefined. You're missing a comma after the 5th element and have a trailing comma after the last. Trying to access properties on that undefined element is throwing the javascript exception that's halting execution on the page. Also, at the initial zoom you have set nothing is visible. Zooming out reveals the map with your markers. Set your initial zoom in your map options to 14.

Markers not showing until map moved slightly or clicked

my (cut down) code is as below. My markers are not showing up until I either click or move the map slightly... is there any way of getting around this so they show up instantly?
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>TSF - Labour Plan </title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
function initialize() {
var centerlatlng = new google.maps.LatLng(53.644638, -2.526855);
var myOptions = {
zoom: 6,
center: centerlatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var latlng = new google.maps.LatLng(51.752927, -0.470095);
var img = "https://dl.dropboxusercontent.com/u/55888592/tsf-logo.gif";
var info = "<img style = 'float: left' src='http://www.tsf.uk.com/wp-content/themes/default/images/tsf-logo.gif'><div style = 'float: right; width: 200px'><p><b>Job Number:</b> </p><p><b>Client:</b> ASDA</p><p><b>Location:</b> HEMEL HEMPSTEAD</p><p><b>Postcode:</b> HP2 4AA</p><p><b>Start Time:</b> 22:0</p><p><b>No of Men:</b> 10.0</p><p><b>Allocated Labour:</b> AB: 5.0, WK: 5.0, : , : , : , : </p><p><b>Job Information: </b>PICK UP TOOLS</div>";
var infowindow = new google.maps.InfoWindow({
});
var marker = new google.maps.Marker({
icon: img,
position: latlng,
map: map,
content: info
});
marker.setMap(map);
google.maps.event.addListener(marker, "click", function(content) {
infowindow.setContent(this.content);
infowindow.open(map,this);
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</body>
</html>
It seems that the problem is still exists in google chrome in most recent version on google map api and marker cluster js.
So I'll post the code which helped in this issue for me.
google.maps.event.addListener(map, 'zoom_changed', function() {
setTimeout(function() {
var cnt = map.getCenter();
cnt.e+=0.000001;
map.panTo(cnt);
cnt.e-=0.000001;
map.panTo(cnt);
},400);
});
feel free to play with value of interval of 400 (in my case less than 400 woudn't fix problem, but higher value - higher lag time)
P.S.
make sure you have defined map variable:
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
I was struggling with the EXACTLY same problem and was so glad to hear other guys have the same problem. I experienced the problem with GMaps V3 in Safari and Firefox as well. I tried your solution and it works for me as well but I used the idle event instead the timeout:
google.maps.event.addListener(map, 'idle', function(event) {
var cnt = map.getCenter();
cnt.e+=0.000001;
map.panTo(cnt);
cnt.e-=0.000001;
map.panTo(cnt);
});
Just add it on initializing Google Maps. There might come up another issue working with infowindows and circles bound to markers. In my case I can set the radius of the circle in the infobox. Jumping out of the input field (with or without changing the radius value) makes red-like markers blue. If you then zoom in/out the original color reappears. To solve this problem you have to change the zoom level quickly (in radius_changed event):
map.setZoom(map.getZoom()-1);
map.setZoom(map.getZoom()+1);
I've resolved this calling repaint on markerclusterer variable twice:
mc.repaint();
map.fitBounds(bounds); // for centering within the marker bounds
mc.repaint(); // repaint for getting it fixed
Hope this helps to anyone still facing the issue.
As per Geocodezips comment, this seems to be a local issue.

XMod Pro - DotNetNuke - Google Maps

I'm trying to get some old code working with the latest Google Maps API. But probably like a majority of the people asking questions, have zero experience with Javascript let alone the API.
If someone could assist, I'd greatly appreciate any help in getting this working properly. Thanks..
The module is the XMod Pro module for DNN. This allows you many options and it's a very powerful module to create items for your webpages, etc. Sometime ago, someone posting information about how to get the Google Maps API working within XMod Pro. The lat and long information about a location is coming from a database where people enter the information about a location. The markers are then put onto the map; which is a standard DIV on the page as well. XMod Pro labels this database information with a double-bracket; e.g. [[Title]] for the title.
When someone clicks on the link for location title, it's to take them to that location on the map and show them information (again from the
database) in the pop-up. This portion isn't working; nor any of the marker information.
I believe the issue is with the JavaScript, but what exactly is causing the issues, I don't know.
Below is the XMod Pro code and most of the pertinent information is stored within the . Thank you again..
<headertemplate>
<a name="HeaderTop"></a>
<div width="150px" height="40px" style="color:black;background-
color:white;padding-bottom:10px;font-family:Georgia;font-size:
14px"><strong>Click an Item</strong></div>
</headertemplate>
<itemtemplate>
<script type="text/javascript">
var i = i + 1;
x[i] = [[Lat]];
y[i] = [[Long]];
d[i] = '<table><tr><td>[[Title]]</td></
tr><tr><td>[[Description]]</td></tr><tr><td>[[Country]]</td></
tr><tr><td>[[Region]]</td></tr><tr><td>[[Email]]</td></tr></table>';
document.write('<div style="padding-bottom:
8px;color:black;background-color:white" width="150px"
onclick="myGclick(' + i + ');">')
</script>
<strong>
<table>
<tr><td colspan="2"><a href="#HeaderTop"><div style="color:
#a41d21;font-size: 13px">[[Title]]</div></a></td></tr>
<tr><td colspan="2">[[Description]]</td></tr>
<tr><td>[[Country]]</td><td>[[Region]]</td></tr>
</table>
</div>
<xmod:scriptblock scriptid="GoogleMapScripts"
registeronce="true" blocktype="ClientScript">
<script src="http://maps.google.com/maps?
file=api&v=2.x&key=ABQIAAAAHrao_r7BKX4cQI0SxCQVHxRXbr2uTTbz5TwhEXAt1Cz65pgUPxQJAHBbHO1MuQeh5aRNkFOL-
Ozptw" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
var x=new Array()
var y=new Array()
var d=new Array()
var myGclick = [];
var gmarkers = [];
// This function picks up the click and opens the corresponding info window
myGclick = function myGclick(i) {
GEvent.trigger(gmarkers[i], "click");
}
oldLoad = window.onload;
window.onload = function load(){
if(oldLoad){
oldLoad();
}
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(40, -98), 3);
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.addControl(new GOverviewMapControl());
// Creates a marker at the given point with the given number label
function createMarker(point, d) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(d);
});
// save the info we need to use later for the side_bar
gmarkers[i] = marker;
return marker;
}
for (var i = 0; i < 999; i++) {
var point = new GLatLng(x[i],
y[i]);
if ((x[i] == undefined)){break}
map.addOverlay(createMarker(point, d[i]));
}
}
}
//]]>
</script>
</xmod:scriptblock>
</itemtemplate>
<footertemplate>
</footertemplate>
<noitemstemplate>
<strong>nothing in table</strong>
</noitemstemplate>
<detailtemplate>
</detailtemplate>
</xmod:template>
Does it bring up any errors/messages in Inspector or Firebug?
In Google Maps API V5, my addMarker code was something like the below, where I've placed the infoWindow content straight into the marker.
function addMarker(map, latitude, longitude, heading, title, content){
var latlong = new google.maps.LatLng(latitude, longitude);
var markerOptions = {
position: latlong,
map: map,
title: title,
clickable: true,
icon: 'marker.png',
};
//create marker object
var marker = new google.maps.Marker(markerOptions);
var infoWindowOptions = {
content: content,
position: latlong
};
//info window object
var infoWindow = new google.maps.InfoWindow(infoWindowOptions);
//add click event listener on marker, to bring up infoWindow
google.maps.event.addListener(marker, "click",function(){
infoWindow.open(map);
});
}
When I was working on this, I used alot the documentation here: developers.google.com/maps/documentation/javascript/overlays for Overlays and Markers
I'm sorry I do not know about XMode Pro, but maybe you could note some differences from the old API to the new.

Javascript google maps

I have multiple locations of my company's regional offices and have to show each location whenever user clicks at a locations like:
location1
location2
location3
When user clicks at location 1 it will show location 1 on the map. I also have those locations in my maps. I have never worked with Google maps before, so I just need some idea to get started.
When your user clicks a link, run a piece a javascript that calls setCenter(latlng:LatLng) on the map to center the map to a certain location.
If you really don't know where to begin, then start by reading the Google Maps API documentation. It's easy to read, and it contains lots of working examples.
You can do something like this: (I'm sure it could be optimized with a for loop, its early/late right now.
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() { //Initalize JS after onload
var map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
var randomPoint1 = new google.maps.LatLng(44.6479, -63.5744); //First Location
var marker1 = new google.maps.Marker({ //Set up marker
position: randomPoint1,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid1'), 'click', //Set up DOM listener 1
function(){
map.setZoom(13);
map.setCenter(marker1.getPosition());
});
var randomPoint2 = new google.maps.LatLng(45.5081, -73.5550); //Second Location
var marker2 = new google.maps.Marker({
position: randomPoint2,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid2'), 'click',//Set up DOM listener 2
function(){
map.setZoom(13);
map.setCenter(marker2.getPosition());
});
var randomPoint3 = new google.maps.LatLng(43.6481, -79.4042); //Third Location
var marker3 = new google.maps.Marker({
position: randomPoint3,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid3'), 'click', //Set up DOM listener 3
function(){
map.setZoom(13);
map.setCenter(marker3.getPosition());
});
map.setCenter(marker2.getPosition());
map.setZoom(5);
}
</script>
</head>
<body onload="initialize()"> <!--Initalize JS after onload--->
Halifax
Montreal
Toronto
<div id="map_canvas" style="height:100%; width:100%"></div>
</body>
</html>
And after I write this I realize the post was from last August. Oh well, may help someone at some point.

Categories

Resources