Set Google maps coordinates as center screen - javascript

I wrote a script which allows an admin to click on a map (google maps api v3) setting up as many locations as he wants, naming them. That is, clicking on the map shows an information window with a form for naming that location. These locations are saved in a database (LatLng coordinates) and show as markers on the map.
Then, users (admin or not) may choose any of these locations from a select box (by name). Once this is selected, there's an option for showing a map with a marker on the selected location. The marker shows correctly, but I would like the map to be centered in that location. That is, the marker in the center of the screen but, instead, it shows in the extreme upper left corner. Actually, initially, the marker isn't even visible. You have to drag the map up and left a little for it to show.
This is rather strange, as I use the same coordinates for both the marker and the center screen. Here's my code (or the relevant part, at least):
var latlng = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.ltn));
var latlng2 = new google.maps.LatLng(parseFloat(location.lat) + 0.025, parseFloat(location.ltn) - 0.05);
var map = new google.maps.Map($('.modal-body', modal)[0], {
'center': latlng,
'zoom': 13,
'mapTypeId': google.maps.MapTypeId.ROADMAP,
});
var marker = new google.maps.Marker({
'position': latlng,
'map': map,
'title': location.name,
});
marker.setMap(map);
Notice how in this sample I don't use the latlng2 value. This is what I tried, but it seems to only work for a given resolution. How can I center the map in those coordinates?
Best regards
Edit:
$(map).focus();
modal.on('shown', function() {
$(window).resize(function() {
google.maps.event.trigger(map, 'resize');
});
google.maps.event.trigger(map, 'resize');
});

I'm not sure if this will work... If that window resize is cause than it might help. I don't know how it will interact with other code.
Add event listener for resize event:
...
marker.setMap(map);
google.maps.event.addListener(map, 'resize', function() {
map.setCenter(latlng);
});

Related

How to identify if the pushpin is visible in the current view/zoom of bingMaps or not? if not visible setView to Location of the pushpin?

I'm using Bing Maps V8 and As per ask, I've to move/pan the bing map to set the visibility of the pushpin. Based on the pushpin location we can directly set the view as shown below but I've adjust/move the bing map only if the current view of bing maps doesn't have the pushpin visible to the naked eye.
this.map.setView({
center: new Microsoft.Maps.Location(pin.lat, pin.long),
});
Could you please share your thoughts on how to identify whether the pin is visible in the current view or not?
Regards & Thank you in Advance.
Get the bounding box of the map, then check to see if it contains your pushpins location. If it doesn't update the map view. Here is a code block that does this.
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {});
var pushpin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(45, -110), null);
map.entities.push(pushpin);
//Get the bounding box of the current map view.
var bounds = map.getBounds();
//Check to see if the bounding box contains the pushpins location.
//And if it doesn't, center the map.
if(!bounds.contains(pushpin.getLocation())) {
map.setView({
center: pushpin.getLocation()
});
}

Google Maps API marker move on scroll and layout style

I'm new in the Google Maps API, I am trying to embed a marker with the address on google maps but I have errors.
https://developers.google.com/maps/documentation/javascript/adding-a-google-map#map
I'm using this documentation and I have copied this code but it doesn't work properly because when you scroll the marker it's not fixed in the map but its move and doesn't stay in the correct place.
Also, the buttons in the left corner MAP and SATELLITE doesn't appear properly, they appear with a background line in the whole map and don't together smaller.
Finally, the + and - button doesn't appear.
Someone could tell me why I have all this problem?
Here is my code:
<script>
function initMap() {
var blitz8 = {lat: 45.806510, lng: 10.109520};
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 18,
center: blitz8
});
var marker = new google.maps.Marker({
position: blitz8,
map: map
});
};
</script>
And here the Live Page:
https://sebalaini.github.io/Blitz8/
Hi I resolve that problem by disabled some css option in your base.scss please check and fix that, check my picture uploaded below

Google Maps API: When infowindow closes, map zooms back to center

I have multiple markers on a google map that -- when clicked on -- open up an infowindow. The problem is, when the infowindow is on the periphery of the map, it resets the center of the map. I want to have the map zoom back to the original center after the infowindow closes.
I'm thinking I could do something like the following:
google.maps.event.addDomListener(infowindow, "close", function() {
google.maps.event.trigger(map, "close");
map.setCenter(new google.maps.LatLng(53.0,-1.0));
}); //pseudo-code
Any tips?
use setzoom
google.maps.event.addDomListener(infowindow, "close", function() {
google.maps.event.trigger(map, "close");
map.setZoom(8);
map.setCenter(new google.maps.LatLng(53.0,-1.0));
}); //pseudo-code
Explaination:
we already defined map so use map object to set zoom level or relocation(setCenter)

fitBounds() shows whole earth (if map is first hidden and then shown)

I have a bunch or markers, and I want to show only the area containing them. I found a long list of similar questions (see at the bottom of the post for some), but none of the solutions works for me. The LatLngBounds is built correctly, but when I call fitBounds the result will be the following:
Instead of:
Can anybody spot an evident error in my code?
var opt = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),opt);
var box = new google.maps.LatLngBounds();
for(var i=0;i<list.length;i++){
var p = new google.maps.LatLng(list[i].lat,list[i].lon);
var marker = new google.maps.Marker({
position: p,
map: map
});
box.extend(p);
}
map.fitBounds(box);
map.panToBounds(box);
Some of the posts I read and tried (list not comprehensive):
Google Maps v3 - Automating Zoom Level?
Google maps V3 custom marker images and fitBounds()
Google Maps with fitBounds don't zoom
fitbounds() in Google maps api V3 does not fit bounds
Edit: this actually happens if (as I do in my application) the map is at first hidden, and showed only later.
I hide it in this way:
$('#map').hide();
and show it:
$('#map').show(function(){
//this is necessary because otherwise
//the map will show up in the upper left corner
//until a window resize takes place
google.maps.event.trigger(map, 'resize');
});
Any clue as to why this happens and how to prevent it (apart from initialising the map when first shown)?
On a side note, if I set zoom and center when declaring the map object (i.e. I don't use fitBounds()) then the map will show correctly, even after a hide/show.
I can't set zoom and center, though, because the list of points is retrieved elsewhere and I don't know where they are beforehand.
Solved (not in a nice way, though).
What I ended up doing was initialising the LatLngBounds with the points when loading the page, but panning and zooming only when showing the map. In this way it works correctly.
E.g.
var box;
function init(){
var opt = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),opt);
box = new google.maps.LatLngBounds();
for(var i=0;i<list.length;i++){
var p = new google.maps.LatLng(list[i].lat,list[i].lon);
var marker = new google.maps.Marker({
position: p,
map: map
});
box.extend(p);
}
}
and then, later (click on a button for example)
function showMap(){
$('#map').show(function(){
google.maps.event.trigger(map, 'resize');
map.fitBounds(box);
map.panToBounds(box);
});
}
It works, but I don't like to have that global var hanging around. I implement the exact same behavior using OpenLayers, and it works correctly without the need for this hack. If anybody has a better solution, please post it and I will accept it if it works.
Thanks to #Engineer and #Matt Handy for helping me eliminate one possible source of errors.
I tried your code in a fiddle, and it works as expected.
So the reason why your code fails must be in the definition of your datapoints (as already suggested by Engineer). Compare your list definition with mine and check if they are different.
Modify to your needs
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
if (map.getZoom() > 16) map.setZoom(16);
google.maps.event.removeListener(listener);
});
same problem, found the reason is that I hide the map (make the container of the map display: none;) before calling fitbounds()
To expand a bit on #JayThakkar 's answer, this worked for me
google.maps.event.addListenerOnce(map, 'idle', function(){
map.fitBounds(bounds);
});
The addListenerOnce function removes the need to call google.maps.event.removeListener(listener);.
And calling map.fitBounds(bounds) inside the listener let us use the calculated bounds's zoom level.

Google Maps API V3 fromDivPixelToLatLng not consistent

I need to place a marker at a fixed pixel location within the map's div. To instantiate a marker, you need a LatLng. I understand that fromDivPixelToLatLng() is the way to convert from pixel co-ordinates to a LatLng, but I can't get it to behave consistently.
I have posted a simple example of my problem at http://www.pinksy.co.uk/newsquare/overlaytest.html. Click on the map to place a marker at 200px/200px. Drag the map around and click again. I was expecting a marker to be placed at 200px/200px every time, but this is not the case.
First I set up the map as usual, in a 600px by 300px div:
var london = new google.maps.LatLng(51.501904,-0.130463);
var mapOptions = {
zoom: 15,
center: london,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
Then I create an overlay:
var overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);
To test fromDivPixelToLatLng(), I create a click event on the map, which attempts to place a marker at pixel location 200px/200px. Regardless of where you drag the map, I was expecting the marker to always be placed at 200px/200px:
google.maps.event.addListener(map, 'click', function(event) {
var pixelLatLng = overlay.getProjection().fromDivPixelToLatLng(new google.maps.Point(200,200));
var marker = new google.maps.Marker({
position: pixelLatLng,
map: map
});
});
However, drag the map around, and you will see that the marker is not always placed at 200px/200px. Any ideas?
Thanks!
After experimentation, I have found that fromContainerPixelToLatLng() is what I'm looking for. For the benefit of others, I have posted an example at http://www.pinksy.co.uk/newsquare/overlaytest2.html.
(For the record, I'm still unsure why fromDivPixelToLatLng behaves the way it does, but never mind!)
Check the demo under:
http://jsbin.com/otidih/51 for some more experiments on this.
To get the logging start the console - most things are logged there.
Detailed explanation from this groups post.
A shorter version below:
The ContainerPixel is calculated relative to your map container. If you pan the map, then the ContainerPixel of LatLngs changes.
The ContainerPixel of things that don't move with the map (float) doesn't change.
For example, the ContainerPixel of the mapCenter stays the same if you don't resize the map:
overlay.getProjection().fromLatLngToContainerPixel(map.getCenter())
The DivPixel is calculated relative to a huge Div that holds the entire tilespace for the world at the current zoom level.
overlay.getProjection().fromLatLngToDivPixel(point)
If you do not change the zoom level and move (pan) the map, then the DivPixel of anything that moves with the map will stay the same. For example the DivPixel of a given city on a map will stay the same, even if you move the map. It will only change when you change the zoom level or cross the international dateline.
Please note that the actual reference point used for calculating the DivPixel gets reset
whenever the map zooms, so the same LatLng can have different DivPixel values even when you come back to the same zoom level.
Also to be considered is the Point value returned from
map.getProjection().fromLatLngToPoint()
which is well explained in the API Reference
It translates from the LatLng cylinder to the big point plane which always stays the same (no matter which zoom level). Given LatLngs will always map to the same Point.
The (0,0) point is the (85.0511287798066,-180) LatLng - where to Google Map cuts of (if you want to know why , read about the Mercator projection)

Categories