Hi in my google map i just draw a one marker when map loads.But then map is zoomed fully in which is really confusing. but when i draw more than one markers map is centered properly and zoomed to a certain level. how can it overcome this.
i have got a loop inside my draw markers function and in that i get only one object that has coordinates. when i get more than one objects from 'markers' map is centered properly. but when it has a only one object to loop. markers gets drawn but map is not well centered and zoomed(zoomed in fully)
function drawMarkers(markerList) {
debugger;
var mapOptions = {
center: new google.maps.LatLng(-24.504710, 134.039231),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var currentLocation;
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
//if (markerList[i].Longitude > 0) {
var data = markerList[i]
var myLatlng = new google.maps.LatLng(data.Latitude, data.Longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.DriverName,
});
var driverCurrentLocation = document.getElementById('<%= hdfDriverCurrentLocation.ClientID %>').value;
latlngbounds.extend(marker.position);
//if (markerList[i].Longitude > 0) {
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
debugger;
var lat = data.Latitude;
var lng = data.Longitude;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
currentLocation = results[1].formatted_address;
}
infoWindow.setContent('<div style="overflow: auto;width: 275px;">' +
'<div id="leftSideMainDiv" class="col25" style="padding-Left:0px; width:22%;">' +
'<div class="col100"><img src="../Images/DriverImages/driver_icon.jpg" height="60" width="60"/></div>' +
'</div>' +
'<div id="RightSideMainDiv" class="col75" style="width:72%;">' +
'<div class="col100" style="font-weight:bold; padding-top:0px; padding-left:0px; font-size:smaller;"> ' + data.DriverName + '</div>' +
'<div style="font-size:smaller; padding-top:15px;">Job Number :' + data.JobId + ' - ' + data.JobType + '</div>' +
'<div style="font-size:smaller;">Delivery Address :' + data.DeliveryAddress + '</div>' +
'<div style="font-size:smaller;">Current Location :' + currentLocation + '</div>' +
'<div style="font-size:smaller;">Last Update :' + data.LastUpdatedTime + '</div>' +
'</div>');
infoWindow.open(map, marker);
}
});
});
})(marker, data);
//}
}
//}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
map.setZoom(5);
}
Related question: How to set zoom level in google map
If you only have one marker (markers.length == 1), then don't call map.fitBounds(). Change:
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
map.setZoom(5);
To:
map.setCenter(latlngbounds.getCenter());
if (marker.length != 1) map.fitBounds(latlngbounds);
map.setZoom(5);
on the initialization of maps set the zoom level, Here the zoom is set to 5
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addDomListener(window, 'load', function () {
map.setZoom(5);
});
Add the map variable outside of map's function scope
var map;
and then modify the line inside your map function-
map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
then after calling your map function drawMarkers(markerList) you need to set the zoom as-
$(document).ready(function(){
drawMarkers(markerList)
google.maps.event.addDomListener(window, 'load', function () {
map.setZoom(5);
});
});
Let me know if that works!
Related
I'm trying to add some infowindow content to my markers on a google map. I can query my server, get some data, put the markers on the map. That works. What doesn't work is that nothing happens when I click on the marker. I would think that the infowindow would popup. Unfortunately, it has been so long since I have done google maps programming, I am effectively starting over. For some reason, the marker's click event is not being called. Any suggestions regarding my dumbness are appreciated. TIA
<script>
var map, geocoder;
var Markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 0.0, lng: 0.0 },
zoom: 12
});
if (!Modernizr.geolocation) {
alert("Your browser sucks. Get a new one, maybe one that is up to date and supports GPS.")
return;
}
else {
navigator.geolocation.getCurrentPosition(show_map);
}
}
function show_map(position) {
map.setZoom(12);
var Latitude = position.coords.latitude;
var Longitude = position.coords.longitude;
map.setCenter({ lat: Latitude, lng: Longitude });
var bounds = map.getBounds();
var url = "/api/xxxxxxxxjsonendpoint";
var lowerLeft = bounds.getSouthWest();
var upperRight = bounds.getNorthEast();
var lat0 = lowerLeft.lat();
var lng0 = lowerLeft.lng();
var lat1 = upperRight.lat();
var lng1 = upperRight.lng();
var geocoder = new google.maps.Geocoder();
var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
$.get(url, data, function (result) {
for (var i = 0; i < result.length; i++) {
var address = result[i].Address1 + " " + (result[i].Address2 != null ? result[i].Address2 : "") + " " + result[i].City + " " + result[i].Province + " " + result[i].PostalCode + " " + result[i].Country;
var marker = new google.maps.Marker({
position: geocodeAddress(geocoder, map, address),
map: map,
title: address
});
var infowindow = new google.maps.InfoWindow({
content: i
});
makeInfoWindowEvent(map, infowindow, "test" + i, marker);
}
});
}
function geocodeAddress(geocoder, resultsMap, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
</script>
Here is the most recent update of my code. Still no worky........
<script>
var map, geocoder;
var Markers = [];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 0.0, lng: 0.0 },
zoom: 12
});
infowindow = new google.maps.InfoWindow();
if (!Modernizr.geolocation) {
alert("Your browser sucks. Get a new one, maybe one that is up to date and supports GPS.")
return;
}
else {
navigator.geolocation.getCurrentPosition(show_map);
}
}
function show_map(position) {
map.setZoom(12);
var Latitude = position.coords.latitude;
var Longitude = position.coords.longitude;
map.setCenter({ lat: Latitude, lng: Longitude });
var bounds = map.getBounds();
var url = "/api/xxxxxxx/yyyyyyyyyy";
var lowerLeft = bounds.getSouthWest();
var upperRight = bounds.getNorthEast();
var lat0 = lowerLeft.lat();
var lng0 = lowerLeft.lng();
var lat1 = upperRight.lat();
var lng1 = upperRight.lng();
var geocoder = new google.maps.Geocoder();
var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
$.get(url, data, function (result) {
for (var i = 0; i < result.length; i++) {
var address = result[i].Address1 + " " +
(result[i].Address2 != null ? result[i].Address2 : "") +
" " + result[i].City + " " + result[i].Province + " " +
result[i].PostalCode + " " + result[i].Country;
var marker = new google.maps.Marker({
position: geocodeAddress(geocoder, map, address),
map: map,
title: address,
content: address
});
makeInfoWindowEvent(infowindow, "test" + i, marker);
}
});
}
function geocodeAddress(geocoder, resultsMap, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function makeInfoWindowEvent(infowindow, contentString, marker) {
(function (zinfowindow, zcontentString, zmarker) {
zinfowindow.setContent(zcontentString);
google.maps.event.addListener(zmarker, 'click', function () {
zinfowindow.open(map, zmarker);
});
})(infowindow, contentString, marker);
}
</script>
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
infowindow.setContent(contentString);
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
Your code crash because when the listener is calling, the value of marker and infowindow have already changed. You can try something like this (just change the makeInfoWindowEvent function):
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(contentString);
infowindow.open(map, marker);
console.log (contentString);
console.log (marker);
});
}
Normally, the output will be always the same for contentString and marker.
In order to pass the real value of the marker, contentString and infowindow, you have to create an IIFE. Like this, the value of the variables will be copy inside the function:
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
(function (zinfowindow, zcontentString, zmarker) {
zinfowindow.setContent(zcontentString);
google.maps.event.addListener(zmarker, 'click', function () {
zinfowindow.open(map, zmarker);
});
})(infowindow, contentString, marker);
}
However, you do not need to pass map as parameter because the value of map is always the same.
Tell me if you have some questions.
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
script(src='/javascripts/jquery.min.js')
script(src='http://maps.google.com/maps/api/js?key=AIzaSyD6MCxtDJOnbE1T6Y09k8Uca1rXHTQ3Bqg&v=3.exp&sensor=true&libraries=places')
script(src='/javascripts/global.js')
h1= title
#loading
p Loading your location
br
#map
input#my-address(type='text')
button#getCords(onclick='codeAddress();') getLat&Long
I write above code in jade template for display the map i.e 'index.jade' and
following file i.e 'global.js' is script file
//Calling the locateme function when the document finishes loading
$(document).ready(function() {
locateMe();
});
//Function to locate the user
var locateMe = function(){
var map_element= $('#map');
if (navigator.geolocation) {
var position= navigator.geolocation.getCurrentPosition(loadMap);
} else {
map_element.innerHTML = "Geolocation is not supported by this browser.";
}
};
//Lets load the mop using the position
var loadMap = function(position) {
var loading= $('#loading');
var latitude=position.coords.latitude;
var longitude=position.coords.longitude;
var myLatlng = new google.maps.LatLng(latitude, longitude);
//Initializing the options for the map
var myOptions = {
center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
//Creating the map in teh DOM
var map_element=document.getElementById("map");
var map = new google.maps.Map(map_element,myOptions);
//Adding markers to it
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'You are here'
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow({
content: "<h2>You are here:</h2>",
//Settingup the maxwidth
maxWidth: 300
});
//Event listener to trigger the marker content
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);});
};
//get lat and log
function codeAddress() {
alert('inside')
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var map = new google.maps.Map(document.getElementById("my-address"),{
center:pyrmont,
zoom:15
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow();
alert(infowindow);
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, 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);
});
};
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api
You are doing Place Search which doesnt return all of the fields that you are using:
http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_responses
In order to get the address, website, etc, you'll also need to call place.getDetails(), passing the Place's reference.
Below is a sample code snippet how to get Places details:
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number);
infowindow.open(map, this);
});
});
}
I have this working multy markers script. Markers are printed on the map but when I click on any marker I can see same info window.. Something wrong in this loop:
function bindInfoWindow(marker, map, infowindow, content) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
function initialize() {
var map;
var locations = <?php echo json_encode($location); ?>;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
// Multiple Markers
var markers = locations;
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow();
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ){
loc_array = markers[i].split(",");
var position = new google.maps.LatLng(loc_array[1], loc_array[2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
draggable: false,
raiseOnDrag: true,
title: loc_array[0]
});
// Info Window Content
content=loc_array[0] + " - <a class='ac' onclick='move("+ loc_array[4] +");' href='#'>" + <?php echo json_encode($lang['view_profile']);?> + "</a><span class='p'>" + <?php echo json_encode($lang['phone']);?> + ": " + loc_array[6] + " </span><span class='p'>" + <?php echo json_encode($lang['address']);?> + ": " + loc_array[5] + ", " + loc_array[7] + ", " + loc_array[8] + "</span>";
bindInfoWindow(marker, map, infoWindow, content);
//infowindow = new google.maps.InfoWindow();
console.log(content);
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(content);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
bounds.extend(marker.position);
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
map.fitBounds(bounds);
google.maps.event.removeListener(boundsListener);
});
}
When I print individual info in console I can see different info windows, but on the map all come same:
console.log(content);
I call initialize() on body load
Please help where I am wrong, Thanks !
First of all declare infowindow globally in following way:
var infoWindow = new google.maps.InfoWindow();
Then after creating marker and content string just call this function:
bindInfoWindow(marker, map, infoWindow, content);
This is the definition of function bindInfoWindow()
function bindInfoWindow(marker, map, infowindow, content) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
Hi I need some help with the following:
I am trying to get two maps to display two different things.
My problem is, on the first map I would like to click on a link in the infowindow (see this) when I do click on that link, I would like that marker to display alone on the second map at its location.
here is my code. Thank you for any help.
$(document).ready(function() {
var map;
var service;
function initialise(location) {
console.log("location:" + location);
var currentLocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
var mapOption = {
center : currentLocation,
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOption);
var marker = new google.maps.Marker({
position : currentLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
//service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
function handleSearchResults(results, status) {
console.log(results)
}
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
});
var content = '<p>See this</p>'
var infowindow = new google.maps.InfoWindow({
content:('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + content)
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
var latitude = this.position.lat();
var longitude = this.position.lng();
console.log(this.position);
});
}
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
var input = $("#search").val();
var query = (input != '' )? input : "restaurant";
performSearch(query);
});
function performSearch(q){
var request ={
bounds: map.getBounds(),
query:String(q)
};
service.textSearch(request, callback);
}
}
function initializer() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
});
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
position : initialLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
}
function initializer_2() {
var mapOption2 = {
center : new google.maps.LatLng(41.923, 12.513),
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
var marker = new google.maps.Marker({
// need the position of marker
//position : currentLocation,
map : map,
});
map = new google.maps.Map(document.getElementById("map-canvas2"), mapOption2);
}
google.maps.event.addDomListener(window, 'load', initializer);
google.maps.event.addDomListener(window, 'load', initializer_2);
$(".getSearch").click(function () {
navigator.geolocation.getCurrentPosition(initialise);
});
});
Hello I'm retrieving data from SqlServerCe so I created foreach loop to create markers - that works it creates multiple markers but now I wanted to add to each of these marker an infowindow. But now whenever I click on marker the infowindow pops-up on the lastly created marker.
<script>
function initialize() {
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
, mapProp);
$(function () {
#foreach (var row in data)
{
<text>
var marker = new google.maps.Marker({ position: new google.maps.LatLng(#row.GeoLat, #row.GeoLong),
map: map });
marker.info = new google.maps.InfoWindow({
content: "test"
});
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
</text>
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
May someone help me with adding infowindow to each created markers?
Thank you for your responding and your time.
This is how I load from SqlServerCe
var db = Database.Open("StarterSite");
var data = db.Query("SELECT DescriptionService,GeoLong,GeoLat FROM services");
var array = new []{data} ;
You can use the following, written in javascript
var infoWindowContent = [];
for(var index=0; index< places.length; index++){
infoWindowContent[index] = getInfoWindowDetails(places[index]);
var location = new google.maps.LatLng(places[index].latitude,places[index].longitude);
bounds.extend(location);
marker = new google.maps.Marker({
position : location,
map : map,
title : places[index].title
});
google.maps.event.addListener(marker, 'click', (function(marker,index){
return function(){
infoWindow.setContent(infoWindowContent[index]);
infoWindow.open(map, marker);
map.setCenter(marker.getPosition());
map.setZoom(15);
}
})(marker,index));
}
function getInfoWindowDetails(location){
var contentString = '<div id="content" style="width:270px;height:100px">' +
'<h3 id="firstHeading" class="firstHeading">' + location.title + '</h3>'+
'<div id="bodyContent">'+
'<div style="float:left;width:100%">'+ location.address + '</div>'+
'</div>'+
'</div>';
return contentString;
}
I added an array infoWindowContent then added the information to the array. You can use the same logic