After maximize google map window, autocomplete doesn't work - javascript

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>

Related

Jquery set marker position by select option data-value

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

How to display certain names in google maps infowindow marker

I'm kind of stuck and was wondering if someone could help, here is a snippet of my code:
function test(person,address)
{
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(43.761539, -79.411079),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow()
var marker, i;
var clatlng, clat, clng;
for (i = 0; i < address.length; i++) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
clat = results[0].geometry.location.lat();
clng = results[0].geometry.location.lng();
clatlng = new google.maps.LatLng(clat, clng);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker) {
//cant add information here dont know why...
return function() {
infowindow.setContent(person[0].cName + "<br>" + results[0].formatted_address);
infowindow.open(map, marker);
}
})(marker));
}
});
}//for
}//function
I'm passing an array of addresses and names. I've been trying to get each marker to display the person's name and address upon clicking on the infowindow of the marker on the map. This is where I'm having issues, I solved the address issue by just using the results[0].formatted_address but am unsure on how to display the specific user to that marker. Any tips would be appreciated.
You need function closure on the name as well as the marker in the click listener for the marker. As the name of the person needs to be available in the callback for the geocoder as well, you need function closure on the geocoder callback function as well.
Related questions
Google Maps V3 - I cannot reconcile closure
JS Geocoder cannot assign Global Variable for Google Maps Variable
proof of concept fiddle
code snippet:
function test(person, address) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(43.761539, -79.411079),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow()
var marker, i;
var clatlng, clat, clng;
for (i = 0; i < address.length; i++) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address[i]
}, (function(name) {
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
clat = results[0].geometry.location.lat();
clng = results[0].geometry.location.lng();
clatlng = new google.maps.LatLng(clat, clng);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker, name) {
//cant add information here dont know why...
return function() {
infowindow.setContent(name + "<br>" + results[0].formatted_address);
infowindow.open(map, marker);
}
})(marker, name));
}
}
})(person[i]));
} //for
} //function
function initialize() {
test(["fred", "george", "frank"], ["New York, NY", "Newark, NJ", "Toronto, CA"]);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Google Place Autocomplete API Showing Blank Map

I'm using the following script to show auto complete place API on my webpage, everything is working fine but map is not showing, i have tried multiple solutions but they won't help in any way here is my script
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<script>
var map;
var marker;
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos,
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerAddress(str) {
document.getElementById("location-text-box").value = str;
}
function initialize() {
var mapOptions = {
zoom: 8
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Get GEOLOCATION
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
marker = new google.maps.Marker({
position: pos,
map: map,
draggable: true
});
google.maps.event.addListener(marker, 'dragstart', function() {
//updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
//updateMarkerStatus('Dragging...');
//updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
// alert("drag ended");
//updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
map.setCenter(options.position);
marker = new google.maps.Marker({
position: options.position,
map: map,
draggable: true
});
// Update current position info.
google.maps.event.addListener(marker, 'dragstart', function() {
//updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
//updateMarkerStatus('Dragging...');
//updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
// alert("drag ended");
//updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// get places auto-complete when user type in location-text-box
var input = /** #type {HTMLInputElement} */
(
document.getElementById('location-text-box'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable: true
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.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(17); // Why 17? Because it looks good.
}
marker.setIcon( /** #type {google.maps.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(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
out put i'm getting is
html
<div style="width:100%; height:100%;">
<input id="location-text-box"/>
<div id="map-canvas"></div>
</div>

Geocoder is automatically panning google map to the left

I am creating a page with a marker that stays fixed at the center of a map, even if the user pans/zoom the map. When the user clicks on the marker it shows the full address of the marker.
The problem is that the infoWindow.setContent() shows a string when I supply one, but pans the map to the left (and doesnt show the infoWindow) when I supply results[0].formatted_address.
The code below is the reverse geocoding I have. The alert function (which I have uncommented) shows the address correctly.
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': input}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
//alert(results[0].formatted_address);
infoWindow.setContent(results[0].formatted_address);
infoWindow.open(map,marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
And my complete Javascript Code is:
var map;
var marker;
var infoWindow = new google.maps.InfoWindow();
function initialize() {
function setUpMap(){
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(22.519422, 88.35741400000006),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
google.maps.event.addListener(map, 'center_changed', function() {
removeMarker();
});
google.maps.event.addListener(map, 'idle', function() {
setMarker();
});
}
function removeMarker(){
marker.setMap(null);
}
function setMarker(){
marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title:"Hello World!"
});
google.maps.event.addListener(marker, 'click', function() {
var input = marker.getPosition();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': input}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
//alert(results[0].formatted_address);
infoWindow.setContent(results[0].formatted_address);
infoWindow.open(map,marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
});
}
setUpMap();
}
google.maps.event.addDomListener(window, 'load', initialize);
I think the problem is that, when the user clicks on the marker, somehow setMarker() gets called. I can't really find out where the problem is coming from. Can anyone help me find it?
It's forced by a interaction between the center_changed-handler and the autoPan of the infoWindow.
When you open a infoWindow the API by default tries to pan the map to be able to show the infoWindow at the best position. But when this happens the center of the map changes, the marker will be removed(that's why you don't see the infowindow). You must set the disableAutoPan-option of the infoWindow to true.
Modified code:
function initialize() {
function setUpMap() {
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(22.519422, 88.35741400000006),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
infoWindow = new google.maps.InfoWindow({
disableAutoPan: true
}),
marker = setMarker(map, infoWindow);
google.maps.event.addListener(map, 'center_changed', function() {
infoWindow.close();
marker.setPosition(this.getCenter());
});
}
function setMarker(map, infoWindow) {
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: "Hello World!"
});
google.maps.event.addListener(marker, 'click', function() {
var input = marker.getPosition();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': input
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[0]) {
console.log(results[0].formatted_address)
//alert(results[0].formatted_address);
infoWindow.setOptions({
content: '<div style="xwidth:200px">' + results[0].formatted_address + '</div>'
});
infoWindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
});
return marker;
}
setUpMap();
}
google.maps.event.addDomListener(window, 'load', initialize);
html {
height: 100%
}
body {
height: 100%;
margin: 0;
padding: 0
}
#map_canvas {
height: 100%
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map_canvas"></div>

Google Maps v3 - Replacing marker as infoWindow display

I've found alot out there on customizing a marker/infoWindow separately but is it possible to make the infoWindow be used as the marker instead? (Only displaying the infoWindow). I've tried toying the marker css as display: hidden; and few other things but no luck.
var mapOptions = {
center: new google.maps.LatLng(37.7831,-122.4039),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var acOptions = {
types: ['establishment']
};
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'),acOptions);
autocomplete.bindTo('bounds',map);
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infoWindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPosition(place.geometry.location);
infoWindow.setContent('<div><strong>' + place.name + '</strong><br>');
infoWindow.open(map, marker);
google.maps.event.addListener(marker,'click',function(e){
infoWindow.open(map, marker);
});
});
This works for me:
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infoWindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
infoWindow.setContent('<div><strong>' + place.name + '</strong><br>');
infoWindow.setPosition(place.geometry.location);
infoWindow.open(map);
});
working example

Categories

Resources