Display Google Map off center - google-maps

We're using Google Maps API to display a map, which is working fine.
I see lots of complaints where the marker on people's maps isn't in the center.
We actually want the opposite, due to the location of the premises on this particular map we'd like to have the map slightly off-center with the location and its marker towards the top-right corner of the map (to clarify, we want to essentially shift the map canvas, not change the actual location of the premises).
Below is the code we're using. The center: latlng is what centers the map, so I know we need to change the center parameter to something else, but I'm not sure what.
<script src="//maps.google.com/maps/api/js?sensor=false&region=GB"></script>
<script>
var geocoder1 = new google.maps.Geocoder;
geocoder1.geocode( { 'address': "360 Any Street, 12345"}, function(results, status) {
myGeocode(results, status, 'map_canvas');
});
function myGeocode(results, status, canvas) {
if (status == google.maps.GeocoderStatus.OK) {
var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById(canvas), myOptions);
var myMarker = new google.maps.Marker({ position: latlng, map: map });
} else {
// alert("Geocode was not successful for the following reason: " + status);
}
}
</script>
<div id="map_canvas" style="width: 600px; height: 600px;"></div>

This is a solution for the current case, but won't set the center to get the desired view when zoom changes. If you want more elegant solution, you can reset the center after each zoom_changed event with a formula including zoom value.
...
var myMarker = new google.maps.Marker({ position: latlng, map: map });
var offsetLat = -0.02;
var offsetLng = -0.02;
map.setCenter(new google.maps.LatLng((map.getCenter().lat() + offsetLat) , (map.getCenter().lng() + offsetLng)));
} else {
...

Related

Google Map api V3, setPosition/setCenter is not working

There are two places where i need to show google maps.
I'm using same code for both maps(I mean I'm reusing same code for both maps).
Below are links where you can find screen shots of those two maps.
https://drive.google.com/file/d/0B2JnvvXsAALUdlVzemRVMzNMajF4OFB1V0JXc0RuN1p4eWFV/view - map1
https://drive.google.com/file/d/0B2JnvvXsAALUVGRhNm1HSldhQnpZT3k4S2I2R1YyQkp4OWZz/view - map2
I'm showing second map(map2) in bootstarp modal
first map(map1) is working fine. But in second map(map2), though I have used setCenter method, marker is not showing at center of the map(instead it is showing at top left corner).
what should i do to place marker at center of the map(in second map)?
below is my code..
initialize: function(options){
//initializing the geocoder
this.geocoder = new google.maps.Geocoder();
this.map;
},
//on show of the view
//onShow is a marionette method, which will be triggered when view is shown
onShow: function(){
var address = this.model.get("address");
//render the map with dummy latLang
this.renderMap();
//render the Map with Proper address
if(address!== ""){
this.renderMapWithProperAddress(address);
}
},
renderMap: function(){
var mapCanvas = document.getElementById("mapCanvas"), self = this,
mapOptions = {
center: new google.maps.LatLng(64.855, -147.833),//dummy latLang
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
mapTypeControl: false,
streetViewControl:false
};
//initializing google map
self.map = new google.maps.Map(mapCanvas, mapOptions);
$("#myModal").on("shown.bs.modal",function(){
google.maps.event.trigger(self.map, "resize");
});
},
renderMapWithProperAddress: function(address){
var self = this,marker;
self.geocoder.geocode( { "address": address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
self.map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: self.map,
position: results[0].geometry.location,
title: address
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
My guess, without seeing your code, is that you need to trigger a map resize event after the bootstrap modal has been shown.
Bootstrap modal
Maps events
$('#myModal').on('shown.bs.modal', function () {
google.maps.event.trigger(map, 'resize');
});
Edit:
Here is a complete and working example. As per my comment, you should 1) Trigger a map resize and 2) set the map center to your marker coordinates.
var center = new google.maps.LatLng(59.76522, 18.35002);
function initialize() {
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: center
});
}
$('.launch-map').on('click', function () {
$('#modal').modal({
backdrop: 'static',
keyboard: false
}).on('shown.bs.modal', function () {
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
});
initialize();
JSFiddle demo

google map is displaying to small in top left corner

In a webapp I´m loading a page (googlemap.asp with the map) with ajax.
I´m loading the "googlemap.asp" in a div with jquery.load and it is only displaying a small map in the top left corner, so its not getting the size 320 x 600 as I have set in the div.
It is not rendering the map correctly when I load it this way.
But if I just load the "googlemap.asp" directly in the browser(without ajax) then it displays right, so I guess I have to refreash it somehow when I load it with ajax?
This is what I have:
<div id="map_canvas" style="height:600px; width:320px;" ></div>
window.onload=googleMaploadScript();
function googleMaploadScript() {
var script =document.createElement("script");
script.type="text/javascript";
script.src="http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
var address1 = document.getElementById('address').value;
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(57.109577,12.286513),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
codeAddress(address1);
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
I guess I load it in the wrong order somehow, and thats why it is not rendering right, or could it be that the div is not visible at start?
Any input appreciated, thanks.
Try changing Height and Width from Script.
For centering add this script to your map script it will center it . But I am also having trouble to bring it from top left to center. In my case when I change the orientation or size the map loads and centered
//script for centering
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
Let me know if it works . Here is the LINK for more information

Google Map API V3: MarkerClusterer won't break down into markers

I have an application where I'm using the Google Map API to display markers for posts made by users using their lat/lon. I employed the MarkerClusterer capability for better organization of the markers, which works but with a bug of sorts.
Essentially, I've been testing this at home so the lat/lon has been the same for all test posts. Before using MarkerClusterer, zooming far into the map would eventually reveal all the markers. Unfortunately, using the MarkerClusterer, if there is, for example, a "5" listed for the number of markers that are very close together such as these test posts, clicking on the cluster reveals nothing. No markers ever appear when these are very close together. To reiterate, these markers do appear without the MarkerClusterer.
I upgraded to MarkerClustererPlus v2.0.9 per another post that described other issues with the MarkerClusterer but that hasn't solved the problem.
Any insight into this issue would be greatly appreciated.
Edit: geocodezip suggested the overlappingmarkerspidifier, which sounds great, but my code is fairly involved and I'm not sure how to incorporate it. Any insight much appreciated. Code follows:
function mainGeo()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition( mainMap, error, {maximumAge: 30000, timeout: 10000, enableHighAccuracy: true} );
}
else
{
alert("Sorry, but it looks like your browser does not support geolocation.");
}
}
var stories = {{storyJson|safe}};
var geocoder;
var map;
var markers = [];
function loadMarkers(stories){
for (i=0;i<stories.length;i++) {
var story = stories[i];
if (story.copy.length > 120) {
story.copy = story.copy.substring(0, 120) + "...";
}
(function(story) {
var pinColor = "69f2ff";
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=S|" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var point = new google.maps.LatLng(story.latitude, story.longitude);
var marker = new google.maps.Marker({position: point, map: map, icon: pinImage});
var infowindow = new google.maps.InfoWindow({
content: '<div >'+
'<div >'+
'</div>'+
'<h2 class="firstHeading">'+story.headline+'</h2>'+
'<div>'+
'<span>'+story.author+'</span><br />'+
'<span>'+story.city+'</span><br />'+
'<span>'+story.topic+'</span><br />'+
'<p>'+story.date+'</p>'+
'<p>'+story.copy+'</p>'+
'<p><a href='+story.url+'>Click to read story</a></p>'+
'</div>'+
'</div>'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,this);
});
markers.push(marker);
})(story);
}
}
function mainMap(position)
{
geocoder = new google.maps.Geocoder();
// Define the coordinates as a Google Maps LatLng Object
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var width = window.innerWidth - 80;
size = width;
// Prepare the map options
var mapOptions =
{
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create the map, and place it in the map_canvas div
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// Place the initial marker
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
loadMarkers(stories);
var markerCluster = new MarkerClusterer(map, markers);
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function error() {
alert("You have refused to display your location. You will not be able to submit stories.");
}
mainGeo();
Perhaps this post in the v3 group: Overlapping markers on your Google Map? Meet OverlappingMarkerSpiderfier might help:
Sounds like the OverlapingMarkerSpiderifier solves your problem.

How to change the street view in google maps 3

Goal: Get the TEXT address and then display the street view and map view at the same time
Ref Site:
http://code.google.com/apis/maps/documentation/javascript/examples/streetview-simple.html
My site:
http://www.iamvishal.com/dev/property/P2154 (pls click the map view to see the map)
Problem: I am able to display the map and the address correctly but instreet view does not change. Any idea why ?
My js variable address hold the text address in this case "323235 Balmoral Terrace Heaton Newcastle Upon Tyne"
function initialize()
{
var fenway = new google.maps.LatLng(42.345573,-71.098326);
var mapOptions = {
center: fenway,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map_canvas"), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 34,
pitch: 10,
zoom: 1
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"),
panoramaOptions);
map.setStreetView(panorama);
var geocoderTwo = new google.maps.Geocoder();
geocoderTwo.geocode({"address":address},function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker
({
map: map,
position: results[0].geometry.location
});
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
}
);
}
Here's how I've created a streetview before:
function createStreetMap(strMapCanvasID, yourLatLng)
{
var panorama;
//once the document is loaded, see if google has a streetview image within 50 meters of the given location, and load that panorama
var sv = new google.maps.StreetViewService();
sv.getPanoramaByLocation(yourLatLng, 50, function(data, status) {
if (status == 'OK') {
//google has a streetview image for this location, so attach it to the streetview div
var panoramaOptions = {
pano: data.location.pano,
addressControl: false,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById(strMapCanvasID), panoramaOptions);
// lets try and hide the pegman control from the normal map, if we're displaying a seperate streetview map
objCreatedMap.setOptions({
streetViewControl: false
});
}
else{
//no google streetview image for this location, so hide the streetview div
$('#' + strMapCanvasID).parent().hide();
}
});
}
Update: and you could call this function directly from within your existing code (I've amended the function to use a LatLng rather than individual latitude and longitude values:
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker
({
map: map,
position: results[0].geometry.location
});
createStreetMap('yourStreetViewDiv', results[0].geometry.location);
}
There are a couple issues with your code. Fix them first:
64 Uncaught ReferenceError: berkeley is not defined
Also, you'll need to set a zoom and mapTypeId options on your Map before anything shows.

How to center a google map around a country if you just have the country name

I have a page about hiking in various countries. I am trying to make a page like that for each country, but not sure how to automatically center the google map around a country and also have it adjust the focus depending on the size of the country.
Here are my problem pages:
http://www.comehike.com/outdoors/country.php?country_id=6&country_name=Belarus
http://www.comehike.com/outdoors/country.php?country_id=1&country_name=United%20States
You see how the centering and focus size is static? That is because I currently use this code to center the map:
function initialize( )
{
var myLatlng = new google.maps.LatLng(37.775, -122.4183333);
var myOptions =
{
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
But that is only because I am not sure how to do it by country name, and adjust the size automatically. How can I do this all by passing a country name into the initialize function?
Thanks!
You can transform country name to the coordinates using Geocoding service. Example provided by Google centers a map but it does not zoom it. To zoom it you should use map.fitBounds() method using LatLngBounds object returned by the geocoder.
This is an example code:
var myLatlng = new google.maps.LatLng(37.775, -122.4183333);
var myOptions =
{
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = "Belarus";
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.bounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});