Google maps zoom level for country - javascript

I'm having a problem working out how to set the zoom level for different countries, I have managed to get the map working and displaying the country, just cannot seem to work out how to set the zoom level.
Any help would be appreciated.
Thanks
George
<script type="text/javascript">
var infowindow = null;
$(document).ready(function () { initialize(); });
function initialize() {
//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.viewport);
// }
//});
var centerMap = new google.maps.LatLng(#Html.Raw(#item.strLatLong));
var myOptions = {
zoom: 4, //<<-------How can I chnage this
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("WeatherMapLocation"), myOptions);
setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
zIndex: sites[3],
html: sites[4]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
</script>

From the documentation on the Geocoder, there is a viewport and a bounds returned in the geocoder's response which can be used to center and zoom the map on the result.
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
working example

Related

Show nearest elements on google map

I am creating a project using google map. My project contains hospital address ( in longitude and latitude) to be stored in database. But I want to show nearest hospital from my current location. And I am unable to figure out how to do it. Please help me with best algorithm and with some code.
Following code is used just to display all hospital address in map now I want is how to show only 3 nearest hospital from my current positiom.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
for (var i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var image = "img/iconHospital.png";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
title: data.district,
animation: animationType
});
}
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
See this example at. I adapted your code accordingly.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: nepalLocation,
radius: 50000,
type: ['hospital']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
if (i == 2) {
break;
}
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>

Cannot drag marker properly in Google Map using JavaScript

I cannot drag marker of Google Map using JavaScript. Here is my code:
geocoder.geocode( { 'address': addrs}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#latitude').val(results[0].geometry.location.lat());
$('#longitude').val(results[0].geometry.location.lng());
var latitude=results[0].geometry.location.lat();
var longitude=results[0].geometry.location.lng();
var title=document.getElementById('googleMap').value;
var desc=title+","+address;
console.log(latitude,longitude);
var markers = [{"lat":latitude,"lng":longitude},{"title": title,"lat":latitude,"lng":longitude,"description":desc}];
// $window.addEventListener('load', onload, false);
// $window.onload = function () {
setTimeout(function(){
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.trigger(map, "resize");
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
google.maps.event.addListener(marker, 'dragend', function (event) {
var latdrag = this.getPosition().lat();
var longdrag= this.getPosition().lng();
console.log('latlong',latdrag,longdrag);
});
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
zoomChangeBoundsListener =
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(12);
}
});
setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000);
},2000);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
Here my issue is I am able to drag the marker but while I am dragging the new marker is coming to droppable place and the first one is still there. Here I need that single marker will only drag to any place and no new marker will create.
You are creating two markers in the same place and dragging the top one.
var markers = [{"lat":latitude,"lng":longitude},{"title": title,"lat":latitude,"lng":longitude,"description":desc}];
creates an array with two elements and in the loop, two markers are created.

Google Maps V3 infowindows displaying wrong content on pins

I am plotting addresses and having an issue with the infowindow showing the right content everytime. Sometimes it shows the right content in the infowindow when clicked and sometimes it shows the wrong information for that map pin.
var map = null;
var markersArray = [];
var markers = [];
var openedInfoWindow ="";
var geocoder = new google.maps.Geocoder();
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(64.85599578876611, -147.83363628361917),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapInfoManual"),
mapOptions);
google.maps.event.addListener(map, 'zoom_changed', function() {
zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom() > 20) // Change max/min zoom here
this.setZoom(18);
google.maps.event.removeListener(zoomChangeBoundsListener);
});
});
addMarker();
}
function addMarker() {
var bounds = new google.maps.LatLngBounds();
for(i=0; i<markersArray.length; i++)
{
CodeAddress(markersArray[i]['address']);
var mytitle = (markersArray[i]['title']);
var myaddress = (markersArray[i]['displayaddress']);
var linkurl = (markersArray[i]['linkurl']);
}
setTimeout(function()
{
for(i=0; i<markers.length; i++)
{
var point = new google.maps.LatLng(markers[i]['lat'], markers[i]['lng']);
var marker = new google.maps.Marker({
position: point,
map: map
});
bounds.extend(point);
var infoWindowContent = "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>"+ mytitle +"</div><div style='margin-bottom:5px;'>" + myaddress + "</div><div><a href='" + linkurl + "/'>More Details</a></div></div>";
openInfoWindow(marker,infoWindowContent)
}
map.fitBounds(bounds);
},2500);
}
// Address To Marker
function CodeAddress(address)
{
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
markers.push({
'lat':lat,
'lng':lng,
'address':address
});
}
});
}
//Info Window
function openInfoWindow(marker,infoWindowContent)
{
var infowindow = new google.maps.InfoWindow({
content: '<div class="cityMapInfoPop">'+infoWindowContent+'</div>'
});
google.maps.event.addListener(marker, 'click', function() {
if(openedInfoWindow !="")
{
openedInfoWindow.close()
}
infowindow.open(map,marker);
openedInfoWindow = infowindow;
});
}
Variables that I pass in:
<script type="application/javascript">
markersArray.push({
"title":'<?php echo $maptitle;?>',
"address":'<?php echo $markerAddress;?>',
"displayaddress":'<?php echo $displayAddress;?>',
"linkurl":'<?php echo $addressUrl;?>'
});
</script>
Your issue is that geocoding is asynchronous. You loop through calling the geocoder on all your addresses, but the order the results are returned in is not predictable.
use function closure to associate the marker with the infowindow
use function closure to associate the address with the marker
use the results of the geocoder inside its callback function.
Note that if you have more that approximately 10 markers in your array you will run into the quota/rate limit of the geocoder.
proof of concept fiddle
code snippet:
var map = null;
var markersArray = [];
var markers = [];
var openedInfoWindow = "";
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
markersArray.push({
"title": 'marker 0',
"address": 'New York,NY',
"displayaddress": 'New York, NY',
"linkurl": 'http://google.com'
});
markersArray.push({
"title": 'marker 1',
"address": 'Boston, MA',
"displayaddress": 'Boston, MA',
"linkurl": 'http://yahoo.com'
});
markersArray.push({
"title": 'marker 2',
"address": 'Newark,NJ',
"displayaddress": 'Newark, NJ',
"linkurl": 'http://mapquest.com'
});
google.maps.event.addDomListener(window, "load", initialize);
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(64.85599578876611, -147.83363628361917),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapInfoManual"),
mapOptions);
google.maps.event.addListener(map, 'zoom_changed', function() {
zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom() > 20) // Change max/min zoom here
this.setZoom(18);
google.maps.event.removeListener(zoomChangeBoundsListener);
});
});
addMarker();
}
function addMarker() {
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markersArray.length; i++) {
CodeAddress(markersArray[i]);
}
}
// Address To Marker
function CodeAddress(markerEntry) {
var mytitle = (markerEntry['title']);
var myaddress = (markerEntry['displayaddress']);
var linkurl = (markerEntry['linkurl']);
geocoder.geocode({
'address': markerEntry['address']
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
bounds.extend(marker.getPosition());
var infoWindowContent = "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>" + mytitle + "</div><div style='margin-bottom:5px;'>" + myaddress + "</div><div><a href='" + linkurl + "/'>More Details</a></div></div>";
openInfoWindow(marker, infoWindowContent);
markers.push(marker);
map.fitBounds(bounds);
} else {
alert("geocode failed: " + status);
}
});
}
//Info Window
function openInfoWindow(marker, infoWindowContent) {
var infowindow = new google.maps.InfoWindow({
content: '<div class="cityMapInfoPop">' + infoWindowContent + '</div>'
});
google.maps.event.addListener(marker, 'click', function() {
if (openedInfoWindow != "") {
openedInfoWindow.close();
}
infowindow.open(map, marker);
openedInfoWindow = infowindow;
});
}
html,
body,
#mapInfoManual {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?ext=.js"></script>
<div id="mapInfoManual" style="border: 2px solid #3872ac;"></div>
Since you didn't provide a working JSFiddle, it was rather difficult to figure out what your problem is. That said, you can look at this JSFiddle that I made for you to review what I'm doing, vs what you're doing.
Why are you using setTimeout() to place your markers? Also, you may have better results if you create an individual infoWindow per marker, instead of using a "global" infoWindow (which is what it looks like you're doing).
If you edit your post to add a working example of your problem, I can help further.
window.places = [{
title: "foo",
address: {
lat: parseFloat("64.85599578876611"),
lng: parseFloat("-147.83363628361917")
},
displayAddress: "101 BLVD",
linkURL: "google.com"
}, {
title: "bar",
address: {
lat: parseFloat("62.85599578876611"),
lng: parseFloat("-147.83363628361917")
},
displayAddress: "202 BLVD",
linkURL: "images.google.com"
}, ]
function initialize() {
"use strict";
var myLatlng = new google.maps.LatLng(window.places[0].address.lat, window.places[0].address.lng),
mapOptions = {
zoom: 4,
center: myLatlng
};
window.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
$.each(window.places, function(i) {
var infowindow = new google.maps.InfoWindow({
content: "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>" + window.places[i].title + "</div><div style='margin-bottom:5px;'>" + window.places[i].displayAddress + "</div><div><a href='" + window.places[i].linkURL + "/'>More Details</a></div></div>"
}),
marker = new google.maps.Marker({
position: new google.maps.LatLng(window.places[i].address.lat, window.places[i].address.lng),
map: window.map,
title: window.places[i].title
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(window.map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<div id="map-canvas"></div>

Google maps how to search for places with button click

i got this code but it appears when the map load, i need that by clicking in a button to hide and show the search result, can an1 help please ?
code:
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);\
EDIT
I trying to create a button that when clicked shows the search result of google places .. I hid the maker and made a function to the button show the marker, but this is not working out
function createMarker(place) {
var placeLoc = place.geometry.location;
var markersr = new google.maps.Marker({
map: map,
icon:icon2,
visible:false,
position: place.geometry.location,
});
function
function showsearch() {
markersr.setVisible(true);
}
button
<input type="checkbox" name="btn2" onClick="showsearch()" class="btn2" >
Please refer the link. http://jsfiddle.net/y829C/1/
var mapOptions = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Update:
Refer the link:http://jsfiddle.net/y829C/11/

Google maps api and geolocation, Javascript and Html

Hey I'm new to the google maps api, and I have an embedded map, i'm using geolocation to get the users lat and long, and i'm then filling in the gaps in the maps api. The map, however doesn't work when I use the generated lat and long, but does work if i just type one in
Non-working code:
var map;
var infowindow;
function initialize() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position)
{
var latlon = new google.maps.LatLng( position.coords.latitude + "," + position.coords.longitude );
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Working code
var map;
var infowindow;
function initialize() {
var latlon = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Any help if appreciated :)
Replace your line:
var latlon = new google.maps.LatLng
(position.coords.latitude + "," + position.coords.longitude);
with
var latlon = new google.maps.LatLng
(position.coords.latitude, position.coords.longitude);
The problem is in concatenating two values into one where constructor expects two parameters.

Categories

Resources