Remove fitBounds from google maps and set zoom level instead [duplicate] - google-maps-api-3

This question already has answers here:
How to set zoom level in google map
(6 answers)
Closed 8 years ago.
I have tried everything but can't work out how to remove the fit to bounds part of this code and set a zoom level instead. The problem is this map is designed for multiple markers but I'm currently only using it with 1 and it zooms in too close.
var gmarkers = [];
var markers = [
[ '<div id="mapcontent">' +
'<a href ="#project0"><h4>43 Short Street</h4>' +
'</div>'
, -27.686478,153.131745]
];
function initializeMaps() {
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [{ featureType: 'all', stylers: [{saturation: -100},{brightness: 5} ]} ],
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
for (i = 0; i < markers.length; i++) {
var pos = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(pos);
marker = new google.maps.Marker({
icon: './img/mapmarker.png',
position: pos,
map: map
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
}
initializeMaps()
function myClick(id){
google.maps.event.trigger(gmarkers[id], 'click');
}
Thanks for your help!

Change
map.fitBounds(bounds);
to (or remove it)
// map.fitBounds(bounds);
Add your desired zoom and center when you initialize the map:
var myOptions = {
// change these per your desired center and zoom.
zoom: 4,
center: new google.maps.LatLng(desiredLat, desiredLng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [{
featureType: 'all',
stylers: [{
saturation: -100
},
{
brightness: 5
}]
}],
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
But if you only have one marker, you should also remove the loop.

Related

Google Maps, Fusion Tables, and Geolocation

I'm having a problem setting a variable in ST_DISTANCE to a variable instead of a number. My goal is to sort fusion table entries by distance to the client and only display the closest 3.
(Also, I would like the window to zoom out and encompass those points as well as point to where the client is. Any hints or links to some recourses would be appreciated).
Here is the Google Maps, Fusion Tables, and Geolocation code:
<script type="text/javascript">
(function() {
if(!!navigator.geolocation) {
var map;
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
navigator.geolocation.getCurrentPosition(function(position) {
var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(geolocate);
});
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions)
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col1",
from: "1JaRXQJ_YJch5Ua6cfZCBpaUEKRnd2jIcHVmcODY",
orderBy: 'ST_DISTANCE(col1, LATLNG("geolocate"))',
limit: 3,
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
} else {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(39.918487877955485, -98.30599773437501),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col1",
from: "1JaRXQJ_YJch5Ua6cfZCBpaUEKRnd2jIcHVmcODY",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
}
})();
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I know this is messy. I don't know javascript.
I would like to know how to put the variable "geolocate" created by:
navigator.geolocation.getCurrentPosition(function(position) {
var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(geolocate);
});
Into the LATLNG place in:
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'Address',
from: '15UY2pgiz8sRkq37p2TaJd64U7M_2HDVqHT3Quw',
orderBy: 'ST_DISTANCE(Address, LATLNG(37.4,-122.1))',
limit: 3
}
Any help is greatly appreciated.
This is just a basic javascript question ...
Make geolocate global, like var map;
var map;
var geolocate;
Remove var in front of your existing geolocate.
Then remove quotes around your usage of geolocate.
orderBy: 'ST_DISTANCE(col1, LATLNG(' + geolocate + ') )',

Google maps v3 geocode multiple custom markers by address or latlng

I need to plot multiple custom map markers using MapsV3 api either by an address or lat/lon. I put together the following code which works ok for lon/lat, but if the data contains an address the geocoder returns nothing. Any ideas on how to fix this.
$(document).ready(function () { initialize(); });
function initialize() {
var centerMap = new google.maps.LatLng(-27.0,133.0);
var options = {
panControl: false,
zoomControl: true,
scaleControl: false,
mapTypeControl: false,
streetViewControl: false,
zoom: 3,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), options);
var data = [
{
'title':'F C Building Construction ...',
'address':'',
'zindex':20,
'lat':'-33.797847',
'lon':'151.259928',
'marker_number':1,
'marker_html':' html content...',
'image': {
url:'//localhost/assets/images/markers/marker_1.png',
size: new google.maps.Size(24, 29),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(10, 29)
}
}];
setMarkers(map, data);
var infowindow = new google.maps.InfoWindow();
}
function showMapPin(i) { }
function setMarkers(map,data) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < data.length; i++) {
setMarker(map, data[i], bounds);
}
map.fitBounds(bounds);
}
function setMarker(map, m, bounds) {
if(m["address"]!="") {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": m["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var siteLatLng = results[0].geometry.location;
}
});
} else {
var siteLatLng = new google.maps.LatLng(m["lat"], m["lon"]);
}
if(siteLatLng) {
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
//shadow: shadow,
icon: m["image"],
title: m["title"],
zIndex: m["zindex"],
html: m["marker_html"]
});
bounds.extend(siteLatLng);
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} // if latlng
}//]]>
After looking back over the code I realized that the variable siteLatLng is within geocode function scope so it never gets passed and it can't be returned. Setting the marker within this function works.

Google Map Marker not being replaced

please excuse a noob at this. When a user clicks on a map, it should place a marker and open an info window - as per this example: http://www.geocodezip.com/v3_example_click2add_infowindow.html
The code below almost works correctly, except that the mark is not replaced - a new one is added. Any ideas really, really gratefully received. Thank you.
<script>
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(0.0000, 0.0000);
var settings = {
zoom: 2,
mapTypeControl:true,
center: latlng,
panControl:true,
zoomControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map'), settings);
function placeMarker(location) {
var marker , i ;
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
icon:'http://www.desperatesailors.com/templates/Live/media/mapicons/info.png',
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng() +
'<br>Only the first four decimal places needed'
});
infowindow.open(map,marker);
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
window.onload = initialize;
</script>
This is a scope issue. You are always delcaring marker in the placeMarker function so if( marker ) will always be false. Move the variable declaration out of that function:
<script>
var marker;
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(0.0000, 0.0000);
var settings = {
zoom: 2,
mapTypeControl:true,
center: latlng,
panControl:true,
zoomControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map'), settings);
function placeMarker(location) {
var i ;
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
icon:'http://www.desperatesailors.com/templates/Live/media/mapicons/info.png',
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng() +
'<br>Only the first four decimal places needed'
});
infowindow.open(map,marker);
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
window.onload = initialize;
</script>
Your placeMarker function creates a new (empty) marker variable in the local scope.
function placeMarker(location) {
var marker , i ;
if ( marker ) {
It will always create a new marker. Change it to:
var marker = null;
function placeMarker(location) {
if ( marker ) {

Google Maps V3 marker with label

How can I add label to my marker if my markers are populated on ajax success each result.
map.gmap('addMarker', { 'position': new google.maps.LatLng(result.latitude, result.longitude) });
I tried like this, but with no success:
map.gmap('addMarker', {
'position': new google.maps.LatLng(result.latitude, result.longitude),
'bounds': true,
'icon': markerIcon,
'labelContent': 'A',
'labelAnchor': new google.maps.Point(result.latitude, result.longitude),
'labelClass': 'labels', // the CSS class for the label
'labelInBackground': false
});
If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..
<script type="text/javascript">
var point = { lat: 22.5667, lng: 88.3667 };
var markerSize = { x: 22, y: 40 };
google.maps.Marker.prototype.setLabel = function(label){
this.label = new MarkerLabel({
map: this.map,
marker: this,
text: label
});
this.label.bindTo('position', this, 'position');
};
var MarkerLabel = function(options) {
this.setValues(options);
this.span = document.createElement('span');
this.span.className = 'map-marker-label';
};
MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
onAdd: function() {
this.getPanes().overlayImage.appendChild(this.span);
var self = this;
this.listeners = [
google.maps.event.addListener(this, 'position_changed', function() { self.draw(); })];
},
draw: function() {
var text = String(this.get('text'));
var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
this.span.innerHTML = text;
this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
this.span.style.top = (position.y - markerSize.y + 40) + 'px';
}
});
function initialize(){
var myLatLng = new google.maps.LatLng(point.lat, point.lng);
var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
map: gmap,
position: myLatLng,
label: 'Hello World!',
draggable: true
});
}
</script>
<style>
.map-marker-label{
position: absolute;
color: blue;
font-size: 16px;
font-weight: bold;
}
</style>
This will work.
I doubt the standard library supports this.
But you can use the google maps utility library:
http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#MarkerWithLabel
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker = new MarkerWithLabel({
position: myLatlng,
map: map,
draggable: true,
raiseOnDrag: true,
labelContent: "A",
labelAnchor: new google.maps.Point(3, 30),
labelClass: "labels", // the CSS class for the label
labelInBackground: false
});
The basics about marker can be found here: https://developers.google.com/maps/documentation/javascript/overlays#Markers
Support for single character marker labels was added to Google Maps in version 3.21 (Aug 2015). See the new marker label API.
You can now create your label marker like this:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.latitude, result.longitude),
icon: markerIcon,
label: {
text: 'A'
}
});
If you would like to see the 1 character restriction removed, please vote for this issue.
Update October 2016:
This issue was fixed and as of version 3.26.10, Google Maps natively supports multiple character labels in combination with custom icons using MarkerLabels.
The way to do this without use of plugins is to make a subclass of google's OverlayView() method.
https://developers.google.com/maps/documentation/javascript/reference?hl=en#OverlayView
You make a custom function and apply it to the map.
function Label() {
this.setMap(g.map);
};
Now you prototype your subclass and add HTML nodes:
Label.prototype = new google.maps.OverlayView; //subclassing google's overlayView
Label.prototype.onAdd = function() {
this.MySpecialDiv = document.createElement('div');
this.MySpecialDiv.className = 'MyLabel';
this.getPanes().overlayImage.appendChild(this.MySpecialDiv); //attach it to overlay panes so it behaves like markers
}
you also have to implement remove and draw functions as stated in the API docs, or this won't work.
Label.prototype.onRemove = function() {
... // remove your stuff and its events if any
}
Label.prototype.draw = function() {
var position = this.getProjection().fromLatLngToDivPixel(this.get('position')); // translate map latLng coords into DOM px coords for css positioning
var pos = this.get('position');
$('.myLabel')
.css({
'top' : position.y + 'px',
'left' : position.x + 'px'
})
;
}
That's the gist of it, you'll have to do some more work in your specific implementation.
You can now add a class name to the marker label via google.maps.MarkerLabel interface.
For example:
const marker = new google.maps.Marker({
position: position_var,
map,
label: {
text: 'label text',
className: "my-label-class",
},
title: "Marker Title",
});
For a full list of options see the google map reference doc:
https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel

set a google marker in sencha touch

I have some problem when i set a marker, I found out this code for generate a google map and it works. But now i want to set a marker with my current position, and the problem is that i don't know where is the google map object, without this the marker isn't displayed.
this.mapg = new Ext.Map({
useCurrentLocation:true,
geo:new Ext.util.GeoLocation({
autoUpdate:true,
timeout:2000,
listeners:{
locationupdate: function(geo) {
center = new google.maps.LatLng(geo.latitude, geo.longitude);
// Set the marker
marker = new google.maps.Marker({
map:geo.map,//??? No idea where is the google map object
position: center
});
if (this.rendered)
this.update(center);
else
this.on('activate', this.onUpdate, this, {single: true, data: center});
},
locationerror: function(geo){
alert('got geo error');
}
}
})
});
After spending a day searching trough google, i founded this solution:
ascom.views.MapG = Ext.extend(Ext.Panel, {
layout:'card',
initComponent: function(){
var infowindow = new google.maps.InfoWindow({
content: 'prova'
});
this.map = new Ext.Map({
mapOptions : {
zoom: 12,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
}
},
useCurrentLocation: true,
listeners: {
maprender : function(comp, map){
var marker = new google.maps.Marker({
position: map.center,
title : 'Infofactory HQ',
map: map
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}
});
this.panel = new Ext.Panel({
layout:'fit',
items:this.map,
dockedItems:[
{
xtype:'toolbar',
title:'Map GO'
}
]
});
this.items = this.panel;
ascom.views.MapG.superclass.initComponent.call(this);
}
});
It's in:
mapg.map
You don't show what mapg is a member of but you could access it explicitly.

Resources