I am creating a google map that has a list of locations and then I want the user to be able to enter their(any) address into the map. Once they enter their address, a new marker must show and the bounds of the map need to update to include the new location.
I've successfully been able to set the new location as a cookie and redraw the bounds of the map on load, however when I try and do this on the geocode input click, the new marker loads, but the bounds seem to only redraw around the new location.
How can I get the bounds to redraw on the input?
Dev site link: http://rosemontdev.com/google-maps-api/
Here is my code:
var locations = [
['Dripping Springs', 30.194826, -97.99839],
['Steiner Ranch', 30.381754, -97.884735],
['Central Austin', 30.30497, -97.744086],
['Pflugerville', 30.450049, -97.639163],
['North Austin', 30.41637, -97.704623],
];
var currentLocationMarker = "http://rosemontdev.com/google-maps-api/wp-content/themes/rm-theme/images/current.png";
var locationMarker = "http://rosemontdev.com/google-maps-api/wp-content/themes/rm-theme/images/pin.png";
function initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locationMarker,
});
var circle = new google.maps.Circle({
map: map,
radius: 3000,
fillColor: '#2B98B0',
fillOpacity: 0.2,
strokeOpacity: 0.25,
});
circle.bindTo('center', marker, 'position');
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoWindow.setContent(locations[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
} //closing for locations loop
var locationValue = Cookies.get('rmLocationCookie-Place');
var longValue = Cookies.get('rmLocationCookie-Long');
var latValue = Cookies.get('rmLocationCookie-Lat');
currentLocationNewMarker = new google.maps.Marker({
position: new google.maps.LatLng(longValue, latValue),
map: map,
icon: currentLocationMarker,
});
bounds.extend(currentLocationNewMarker.position);
map.fitBounds(bounds);
} //closing initMap
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
var infoWindow = new google.maps.InfoWindow();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
var currentLocationData = [];
var bounds = new google.maps.LatLngBounds();
var currentLocationName = 'Current Location';
var currentLocationLong = results[0]['geometry']['bounds']['f']['b'];
var currentLocationLat = results[0]['geometry']['bounds']['b']['b'];
currentLocationData.push(currentLocationName, currentLocationLong, currentLocationLat);
//Location Value Entered
Cookies.set('rmLocationCookie-Place', address);
//Geocoded Long
Cookies.set('rmLocationCookie-Long', currentLocationLong);
//Geocoded Lat
Cookies.set('rmLocationCookie-Lat', currentLocationLat);
var locationValue = Cookies.get('rmLocationCookie-Place');
if(locationValue === undefined){
console.log('no cookie set');
$('#cookie-notice').html('Your location is not saved.');
}
else{
$('#cookie-notice').html('Your location is saved as ' + locationValue +'');
}
updatedCurrentLocationMarker = new google.maps.Marker({
position: new google.maps.LatLng(currentLocationLong, currentLocationLat),
map: map,
icon: currentLocationMarker,
});
bounds.extend(updatedCurrentLocationMarker.position);
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
Try this:
Keep track of the original bounds before each geocode.
Then once the geocode completes pan to the marker and get the new map bounds the.
The idea is then to union the old and new bounds together using the. Union method then use the result as tour new map boundary.
originalbounds.union(newbounds)
Related
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.
I have been playing around with the twitter API getting random tweets or even geo tagged tweets and also with the google maps API. However I want to combine this two and try and show geo tagged tweets on a google map. Here is my code for getting the geo tagged Tweets which work fine.
var geo = (geo.coordinates[0], geo.coordinates[1])
//var geo = (34.052234, -118.243685)
client.get('search/tweets', { q:string.teamname, geocode: geo, count: 5},
function searchTweets(err, data, response) {
for(var index in data.statuses){
var tweet = data.statuses[index];
console.log(tweet.text);
console.log(tweet.geo.coordinates)
}
});
On a different file, I generated a map based on Longitude and Latitude, and I had the understanding that once I had retrieved the coordinates for the tweets, I could represent the tweets on a Google Map in the same way. However, my code is not working. My question is, how would I combine both pieces of code to generate a map which is marked with geo located Tweets?
function initialize() {
var myLatlng = new google.maps.LatLng(geo.coordinates[0], geo.coordinates[1]);
var mapOptions = {
center: myLatlng
zoom: 10,
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Tweet});
var infowindow = new google.maps.InfoWindow({
content: 'Geo tagged Tweet',
maxWidth:200 });
infowindow.open(map,marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker); });
}
google.maps.event.addDomListener(window, 'load', initialize);
I would do something like this (untested - I'm just writing down some thoughts).
1) You should strip down init so that it just contains the map set up. Ensure map is declared outside of the function, and include a call to the function that fetches your data using the lat/lng data.
var map;
function initialize() {
var lat = geo.coordinates[0];
var lng = geo.coordinates[1]
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = { center: myLatlng, zoom: 10 }
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
getData(lat, lng, processData);
}
2) You wrap your data fetching code in a new function declaration, which accepts lat/lng data, and a callback.
function getData(lat, lng, callback) {
client.get('search/tweets', { q:string.teamname, geocode: geo, count: 5},
function searchTweets(err, data, response) {
callback(data.statuses);
}
)
};
3) Process the tweet information. For each tweet create a marker (add the marker to an array of markers) and update the map
function processData(data) {
var markers = [];
for (var i = 0, l = data.length; i < l; i++) {
var marker = new google.maps.Marker({
id: i,
position: myLatlng(data[i].geo.coordinates[0], data[i].geo.coordinates[1),
map: map,
title: "Tweet"
});
markers.push(marker);
var infowindow = new google.maps.InfoWindow({
content: data[i].text,
maxWidth: 200
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}
Hi i'm trying to get markers latlon from ajax, i m getting ajax data every second and also able to create marker within radius , now i'm facing problem with updating marker positions as in current new marker created and old one also showing. Pls help to update markers which i am getting from ajax and remove extra.
var map = null;
var geocoder = null;
var markers = {};
var infoWindow = null;
var minZoomLevel = 16;
jQuery('#search').click(function() {
var address = jQuery('#address').val() || 'India';
if (map === null)
initializeMap();
searchAddress(address);
});
function initializeMap() {
var mapOptions = {
zoom: minZoomLevel,
draggable: true,
disableDefaultUI: true,
scrollwheel: true,
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
});
}
google.maps.event.addListener(map, "idle", function(event) {
searchStoresBounds();
});
geocoder = new google.maps.Geocoder();
infoWindow = new google.maps.InfoWindow();
}
function searchAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var latlng = results[0].geometry.location;
map.setCenter(latlng);
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
searchStoresBounds();
} else {
alert('Geocode was failed: ' + status);
}
});
}
setInterval(function searchStoresBounds() {
var bounds = map.getCenter().toUrlValue();
var url = './store.php';
var parameter = { bounds: bounds };
jQuery.ajax({
url: url,
data: parameter,
dataType: 'json',
success: showStores
});
}, 1000);
function showStores(data, status, xhr) {
if (data['status'] != 'OK')
return;
var id;
// add markers for new stores
for (id in data['data']) {
if (markers[id] === undefined)
createMarker(id, data['data'][id]);
}
var b = map.getBounds();
// remove markers out of the bounds
for (id in markers) {
if (! b.contains(markers[id].getPosition())) {
markers[id].setMap(null);
delete markers[id];
}else{createMarker(id, data['data'][id]);}
}
}
function createMarker(id, store) {
var latlng = new google.maps.LatLng(
parseFloat(store['lat']),
parseFloat(store['lng'])
);
var html = "<b>" + store['address'] + "</b>";
var x = store['distance'];
var y = 1000;
var z = x * y;
var m = 85;
var t = z / m;
document.getElementById("demo").innerHTML = Math.ceil(t);
var headm = store['bearing'];
var car = "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-
2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z
M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z
M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z
M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z";
var icon = {
path: car,
scale: .7,
strokeColor: 'White',
strokeWeight: .4,
fillOpacity: 1,
fillColor: '#333333',
offset: '5%',
rotation: parseInt(headm),
// rotation: parseInt(heading[i]),
anchor: new google.maps.Point(10, 25) // orig 10,50 back of car, 10,0 front of car, 10,25 center of car
};
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers[id] = marker;
}
You are facing the issue due to this part
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
Everytime you get data from ajax it creates a new marker.
Add the following declaration at the top of your js page
var marker;
and change the marker creation to the following
if(marker)
{
marker.setMap(null);
}
marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
Before you create a new marker the previous one is removed from the map. The if(marker) part is needed to check if a marker instance has been created because the first time that you run there will be no marker and you will get an error while trying to remove the marker.
Edit 1 :
As you have multiple markers you will need to store an array of markers and remove them before adding new markers on map
At the top of the page you will need to declare
var markerArray = new Array();
Just before you add the markers you will need to clear the previous markers
for(var i = 0; i<markerArray.length; i++)
{
markerArray[i].setMap(null);
}
markerArray = new Array()
After that will be your current code
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
markerArray.push(marker);
You will need to add the marker to the markerArray so that it can be cleared the next time your code executes.
its working fine but i have one problem which is that when i open a info window its opened but when i open other info window. the last one info window still opened. but i want to close it when we open new inf window
<script>
window.onload = getMyLocation;
var geocoder;
var map;
function getMyLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
} else {
alert("Oops, no geolocation support");
}
}
//This function is inokved asynchronously by the HTML5 geolocation API.
function displayLocation(position) {
//The latitude and longitude values obtained from HTML 5 API.
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
//Creating a new object for using latitude and longitude values with Google map.
var latLng = new google.maps.LatLng(latitude, longitude);
showMap(latLng);
addNearByPlaces(latLng);
createMarker(latLng);
//Also setting the latitude and longitude values in another div.
// var div = document.getElementById("location");
//div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}
function showMap(latLng) {
geocoder = new google.maps.Geocoder();
var markers = [];
//Setting up the map options like zoom level, map type.
var mapOptions = {
center: latLng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Creating the Map instance and assigning the HTML div element to render it in.
map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
// Create the search box and link it to the UI element.
}
function addNearByPlaces(latLng) {
var nearByService = new google.maps.places.PlacesService(map);
var request = {
location: latLng,
radius: 500,
types: ['atm']
};
nearByService.nearbySearch(request, handleNearBySearchResults);
}
function handleNearBySearchResults(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(place.geometry.location, place);
}
}
function createMarker(latLng, placeResult) {
var markerOptions = {
position: latLng,
map: map,
animation: google.maps.Animation.DROP,
clickable: true
}
//Setting up the marker object to mark the location on the map canvas.
var marker = new google.maps.Marker(markerOptions);
if (placeResult) {
var content = "<b>Name : </b>"+placeResult.name+"<br/><b>Address : </b>"+placeResult.vicinity+"<br/><b>Type : </b>"+placeResult.types+"<br/> Rating : "+placeResult.rating+"<br/>" ;
addInfoWindow(marker, latLng, content);
}
else {
var content = "You are here: ";
addInfoWindow(marker, latLng, content);
}
}
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 latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
<!-- alert("Latitude: " + latitude + "\nLongitude: " + longitude); -->
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
var latLngs = new google.maps.LatLng(latitude, longitude);
addNearByPlaces(latLngs);
createMarker(latLngs);
});
}
function addInfoWindow(marker, latLng, content) {
var infoWindowOptions = {
content: content,
position: latLng
};
var infowindow = new google.maps.InfoWindow(infoWindowOptions);
google.maps.event.addListener(marker, 'click', function() {
if(!marker.open){
infowindow.open(map,marker);
marker.open = true;
}
else{
infowindow.close();
marker.open = false;
}
});
}
</script>
I use something like this for closing all infoWindows:
infoWindows = []; //variable to store all infoWindows
function createMarker( map, latlng, title, content, icon ) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon,
title: title
});
var infoWindow = new google.maps.InfoWindow({
content: content
});
infoWindows.push( infoWindow );
google.maps.event.addListener(marker, 'click', function () {
closeAllInfoWindows();
infoWindow.open(map, marker);
});
}
function closeAllInfoWindows() {
for (var i=0;i<infoWindows.length;i++) {
infoWindows[i].close();
}
}
below is my code, where I've created a geolocation marker and a marker which the user can drag around the map.
I'm wondering what I need to do in order to keep the location of the dragged marker, if the user refreshes. Below is my code:
function initialize() {
var locations = [
['Your Hostel Is Here', 54.911615,-1.377025,],
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(54.911615,-1.377025),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
draggable: true
});
localStorage.setItem('marker', marker);
var retrievedmarker = localStorage.getItem('marker');
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
// Check if user support geo-location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geolocpoint = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 8,
center: geolocpoint,
mapTypeId: google.maps.MapTypeId.HYBRID
}
// Place a marker
var geolocation = new google.maps.Marker({
position: geolocpoint,
map: map,
title: 'Your geolocation',
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
You need to store the lat long value of a marker object in string, rather than the object. Furthermore, your need to listen to the marker mouseup event to store the marker value for later display.
Add this event:
//Record the new marker position
google.maps.event.addListener(marker, 'mouseup', function() {
localStorage.setItem('marker', marker.position.lat() + "," + marker.position.lng());
var retrievedmarker = localStorage.getItem('marker');
});
Edit the following code section:
//Get the last recorded marker position for display
var retrievedmarker = localStorage.getItem('marker');
mylatlng = retrievedmarker.split(",");
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
//position: new google.maps.LatLng(locations[i][1], locations[i][2]),
position: new google.maps.LatLng(mylatlng[0], mylatlng[1]),
map: map,
draggable: true
});
Note: I didn't check for the localStorage key existence, please make sure you check for it before the value retrieval.