Jquery set marker position by select option data-value - javascript

I want to ask I have a google map search function, then I want to add the function to set the marker location by using select options.
here my function
var map = null;
var marker = null;
$('#pilih_customer').on('change', function() {
lati = $(this).find(':selected').attr("data-latitude");
lngi = $(this).find(':selected').attr("data-longitude");
name = $(this).find(':selected').attr("data-name");
bindDataToForm(name, lati, lngi);
map.setCenter(new google.maps.LatLng(lati, lngi));
map.setZoom(17);
marker.setPosition(place.geometry.location);
})
function initialize() {
var latlng = new google.maps.LatLng(-6.189623, 106.835454);
var map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 17
});
var marker = new google.maps.Marker({
map: map,
position: latlng,
draggable: true,
anchorPoint: new google.maps.Point(0, -29)
});
var input = document.getElementById('location');
// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var geocoder = new google.maps.Geocoder();
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(20);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
bindDataToForm(place.formatted_address, place.geometry.location.lat(), place.geometry.location.lng());
infowindow.setContent(place.formatted_address);
infowindow.open(map, marker);
});
// this function will work on marker move event into map
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({
'latLng': marker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
bindDataToForm(results[0].formatted_address, marker.getPosition().lat(), marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
function bindDataToForm(address, lat, lng) {
document.getElementById('location').value = address;
document.getElementById('lat').value = lat;
document.getElementById('lng').value = lng;
$('#calculate').attr('disabled', false);
}
google.maps.event.addDomListener(window, 'load', initialize);
<select class="form-control" id="pilih_customer" style="border-radius: 5px;" name="id_customer" required="">
<option value=""> *select </option>
<option value="817" data-latitude="-8.16837" data-longitude=" 113.45152" data-name="A`A Frozen Food"> A`A Frozen Food </option>
<option value="861" data-latitude="-8.16836" data-longitude=" 113.45156" data-name="AA Frozen Food "> AA Frozen Food </option>
</select>
my problem now is how can I move the marker based on the select option that I choose?
what should i change so my code can be work ? here I use data-latitude and data-longitude

Remove the var on marker on initialize() this will initiate on that function only.
$('#pilih_customer').on('change', function() {
/*
- Add + before $(this) to convert the value from string to number
- You can pass object (LatLngLiteral) on setPosition
*/
var lati = +$(this).find(':selected').attr("data-latitude");
var lngi = +$(this).find(':selected').attr("data-longitude");
var name = $(this).find(':selected').attr("data-name");
.....
marker.setPosition({lat: lati,lng: lngi});
})
function initialize() {
.....
/*
- Remove var. Do not initiate the marker variable again
*/
marker = new google.maps.Marker({
map: map,
position: latlng,
draggable: true,
anchorPoint: new google.maps.Point(0, -29)
});
.....
}
Doc: Google Map Marker

Related

After maximize google map window, autocomplete doesn't work

I'm trying to use google map with mvc in my project.
I can find the location by typing in textbox while map is minimized.
The location is showed automatically.
However the location isn't showed automatically in the maximize state.
Here is my code :
function initialize() {
var latlng = new google.maps.LatLng(Lat, Long);
var map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 13
});
var marker = new google.maps.Marker({
map: map,
position: latlng,
draggable: true,
anchorPoint: new google.maps.Point(0, -29)
});
var input = document.getElementById('searchInput');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var geocoder = new google.maps.Geocoder();
var autocomplete = new google.maps.places.Autocomplete(input);
//Set initial restrict countries.
autocomplete.setComponentRestrictions(
{ 'country': ['mm'] });
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
autocomplete.addListener('place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
infowindow.setContent(place.formatted_address);
infowindow.open(map, marker);
});
// this function will work on marker move event into map
google.maps.event.addListener(marker, 'dragend', function () {
geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Screenshot :
Screenshot 1
Screenshot 2
Set a z-index for .pac-container that is above the map (warning undocumented behavior, may change with future releases of the API)
.pac-container {
z-index: 2147483648;
}
proof of concept fiddle
code snippet:
function initialize() {
var latlng = new google.maps.LatLng(21.958828, 96.089103);
var map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 13
});
var marker = new google.maps.Marker({
map: map,
position: latlng,
draggable: true,
anchorPoint: new google.maps.Point(0, -29)
});
var input = document.getElementById('searchInput');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var geocoder = new google.maps.Geocoder();
var autocomplete = new google.maps.places.Autocomplete(input);
//Set initial restrict countries.
autocomplete.setComponentRestrictions({
'country': ['mm']
});
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
infowindow.setContent(place.formatted_address);
infowindow.open(map, marker);
});
// this function will work on marker move event into map
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({
'latLng': marker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
z-index: 0;
}
#searchInput {
top: 15px;
left: 120px;
}
.pac-container {
z-index: 2147483648;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="searchInput" />
<div id="map"></div>

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.

Autocompletion en show on map

I have tried to make autocompletion for my application and show this to my Google maps but it doesn't works well.
The code is in a seperate js file called autocomplete.js
I already have a google maps in app so I want to use the same.
The id of google map is: googleMap
The id of search button is: autosearch
The id of input is: autoinput
"use strict";
var input = document.getElementById('autoinput');
var options = {
bounds: defaultBounds,
types: ['establishment']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
var input = document.getElementById('autoinput');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'be'}
};
function fillInAddress() {
var place = autocomplete.getPlace();
var defaultBounds = document.getElementById('googleMap')(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('autoinput');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
};
I changed code etc but i guess i deleted something that i need.
This is the other js file for geolocation called locationSearch.js:
var google;
$( document ).ready(function() {
zoekLocatie();
});
function zoekLocatie() {
var output = document.getElementById("googleMap");
navigator.geolocation.getCurrentPosition(success, error);
output.innerHTML = "<p>Looking for your location...</p>";
if (!navigator.geolocation) {
output.innerHTML = "<p>Your browser doesn't support geolocation</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var mapProp = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 18,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
geocodeLatLng(geocoder, map, infowindow);
function geocodeLatLng(geocoder, map, infowindow) {
var input = latitude + "," + longitude;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(18);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
address.innerHTML = results[1].formatted_address;
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
you have a error here
use strict";
you should remove the "
And where you call your google map function ?

how to close info window when other info window open in google map javascript

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();
}
}

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/

Categories

Resources