Google map marker not showing in bootstrap modal - javascript

google map marker not showing in bootstrap modal.
this is my jquery code :
function map_init() {
if(!$('body').data('map')){
var var_mapoptions = {
zoom: 6,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
mapTypeIds: ['roadmap', 'terrain']
}
};
$('body').data('map',new google.maps.Map($('<div id="map"/>')[0],
var_mapoptions));
}
return $('body').data('map');
}
var Lat;
var lon;
$(document).on('click','a[data-map]',function(){
var data=$(this).data('map'),
map=map_init();
var geocoder = new google.maps.Geocoder();
var address = data;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
Lat = latitude;
lon = longitude;
});
$('#map_modal')
.find('.modal-body')
.append(map.getDiv())
.end()
.find('.modal-title')
.text(data.Name)
.end()
.one('shown.bs.modal',function(){
google.maps.event.trigger(map, "resize");
map.setCenter({lat:Lat,lng:lon});
});
})
.modal('show');
});
it's showing modal , but not showing the map marker. the latitude and longitude values are came from php code( that is from while loop value).

I believe you did not created any Google Maps Javascript API Markers object.
A marker identifies a location on a map. By default, a marker uses a
standard image. Markers can display custom images, in which case they
are usually referred to as "icons."
I would suggest to edit and add this code inside this line:
if ( status == google.maps.GeocoderStatus.OK ) {
//add marker code here
}
code to be added:
var marker = new google.maps.Marker({
positions : new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng() ),
map: map,
title: 'I am a marker :)'
});
And your Marker will appear.

Related

Google Maps geocode() loop to place markers

I have an array with location data with one of the items being an address - ie. "123 Main Street, San Francisco, California". I want to take that address, turn it into coordinates, then use those coordinates to plot a marker on the map. To do this, I know I need to use geocode(), so I added that part into my loop.
If I were to use latitude and longitude in my array instead of the address, I can get this to work fine. But, since I added geocode() into my loop, I can only get the first location in the array to display a marker.
I have seen some similar questions on here that suggest using callback() but I did not understand it. I've also seen a suggestion to add a delay to geocode() of 0.5 seconds which worked for the poster, but comments said it may not load all locations on slower internet speeds.
How can I fix this to show all locations in the correct way?
// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
// Create the map canvas with options.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
scrollwheel: false,
draggable: true,
mapTypeControl: false,
zoom: zoomlevel,
center: new google.maps.LatLng(40.577453, 2.237408), // Center the map at this location.
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
// For each location in the array...
for (i = 0; i < locations.length; i++)
{
// Get the coordintes for the address.
var geocoder = new google.maps.Geocoder();
var address = locations[i][5]; // ***This variable will output the address.***
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location_latitude = results[0].geometry.location.lat();
var location_longitude = results[0].geometry.location.lng();
// Create the map marker icon (SVG file).
var marker_icon = {
url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
anchor: new google.maps.Point(25,50),
scaledSize: new google.maps.Size(50,50)
}
// Place the marker on the map.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location_latitude, location_longitude),
map: map,
icon: marker_icon
});
}
});
}
}
This is how I am placing map markers on Google Maps:
<script type="text/javascript">
let map;
let parameters;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: #Model.Latitude , lng: #Model.Longitude },
zoom: #Model.Zoom,
});
#foreach (var asset in dbService.Assets)
{
#if (asset.State != Models.AssetState.deleted)
{
#:parameters = 'Id = #asset.Id\n' + 'Temperature = #asset.Temperature\n' + 'Moisture = #asset.Moisture\n';
#:setMarker('#asset.Latitude', '#asset.Longitude', '#asset.State');
}
}
}
function getIconByState(state) {
if (state == 'non_functional') {
return 'non-functional.png';
}
else if (state == 'under_maintenance') {
return 'under-maintenance.png';
}
else if (state == 'functional') {
return 'functional.png';
}
}
function setMarker(lat, lng, state) {
var markerjs = new google.maps.Marker({
icon: getIconByState(state),
position: new google.maps.LatLng(lat, lng),
});
markerjs.setMap(map);
let infowindow = new google.maps.InfoWindow({
content: parameters,
});
markerjs.addListener("click", () => {
infowindow.open(map, markerjs);
});
}
</script>
//this is how to use the callback
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap&libraries=&v=weekly"
defer></script>
In this code, I use the latitude and longitude to place a marker on the Map.
If you want to extract the latitude and longitude from an address, then use geocoder API in the following way:
<script type="text/javascript">
function setCoordinates() {
let address = document.getElementById('zip').value;
if (address) {
let geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('latitude').value = results[0].geometry.location.lat();
document.getElementById('longitude').value = results[0].geometry.location.lng();
}
else {
console.log('geocoding failed');
}
});
}
}
else {
alert('Please enter postal code to use this functionality');
}
}
</script>

create marker with geocode in function JS

So, i am trying to create a marker on my google map. In my page html/jsp i have the code of the map where i call a function js : createOfficiel(address, map);
In this function i tried to geocode the string address and create a marker thanks to the geocode. But it doesn't seem to work, can you tell me why ?
Thank you :)
Here is my function .js :
function createOfficiel (address, map){
var address = document.getElementById('address').value;
var officiel = 'images/officiel.png';
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({"address": address},
function(results) {
var marqueurOfficiel = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
icon: officiel,
optimized: false
});
});
}
}
well i just find it, the main problem _ i think _ was the position value of the marker. I splited the position in lat + lng.
So here is the code working :
function createOfficiel (address, map){
var officiel = 'images/officiel.png';
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
"address": address},
function(results) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var marqueurOfficiel = new google.maps.Marker({
position: {
lat: lat,
lng: lng
},
map: map,
icon: officiel,
optimized: false
});
});
}
}

Google Geocoder - Add co-ordinates to fields

I am trying to find some minamilistic google geocoding script. The ones I have found are very large and complicated, but this one is very simple. The only thing it doesnt do is actually put the co-ordinates in two input boxes like the others.
Here is the code working:
http://jsfiddle.net/Rr5PL/89/
How do I get it to put the co-ordinates in a long / lat input field? It must have them stored because it uses them to display on the map.
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
}
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 marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
You can simply take them from the Javascript variables. You don't need input fields.
var lat = results[0].geometry.location.lat();
var lon = results[0].geometry.location.lng();
var url = 'www.url.com/search?lon='+lon+'&lat='+lat;
In order to put latitude and longitude in text fields you need to create 2 text boxes first and put latitude and longitude.
var latitude= results[0].geometry.location.lat();
var longitude=results[0].geometry.location.lng();
This jsfiddle shows an example.
http://jsfiddle.net/harendra/njDvn/6/
It's easy, try this
var loc=results[0].geometry.location;
document.getElementById('latLng').value=loc.lat()+', '+loc.lng();
DEMO.

Google maps placemark doesn't replace old placemark

I'm developing a web page with a Google Maps application and there is something that I'm having trouble with. As it stands, the web page has a functional map (without any layers) and a search bar. I'm new to programming so hopefully there is a quick fix that I'm missing.
When I look up an address, the placemark is is positioned where it is supposed to be. However, when I make a second search with a different address, the placemark of the first search remains visible so that there are two placemarks on the screen. How can I make a new placemark replace the old one?
<script type="text/javascript">
var geocoder;
var map;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (55.1667, -114.4000);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
marker = new google.maps.Marker({map:map});
}
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);
marker.setposition(results [0].geometry.location);
map.setZoom(16);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
One way to achieve what you describe is with a global marker variable. Since the codeAddress function is calling new google.maps.Marker every time it runs, you will get a new marker each time.
Instead, use the setPosition function of the global marker to move it around.
var geocoder;
var map;
// ADDED
var marker;
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (55.1667, -114.4000);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
// ADDED
marker = new google.maps.Marker({ map: map });
}
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);
// CHANGED
marker.setPosition(results [0].geometry.location);
map.setZoom(16);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

Google Maps v3 - How to center using an address on initialize?

Using Google Maps API v3, is there a way to set the center of the map on initialize? I have a workaround using this code:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
codeAddress('germany');
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
});
}
The only problem is that when it initializes, it centers it to the "latlng" for a split second. I'm can't figure out how to set the center in "myOptions". I though I could return "results[0].geometry.location" from the codeAddress function and pass it to myOptions, but that doesn't work.
Thanks for any help.
Update
Since I can't remove "center" altogether, I'm wondering if there's a way to pass the address to the options.
From Google API:
To initialize a Map, we first create a Map options object to contain map initialization variables.
This object is not constructed; instead it is created as an object literal. There are two required
options for every map: center and zoom.
Well a simple solution could be to initialize the map in your codeAddress function:
var geocoder, map;
function codeAddress(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 8,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
});
}
This should solve the problem.
This is an amazing answer that really helped me get super far. The only issue now is that setCenter is no longer valid in the JavaScript API. Here's my example using fitBounds, ES6 arrow functions to access a this reference to the google map angular component, and finally implementing ngOnChanges to listen for changes to an address text field and re-render the map accordingly.
ngOnChanges(changes: SimpleChanges) {
const newFormattedAddress = changes['formattedAddress']?.currentValue;
if (!newFormattedAddress) {
return;
}
// if we received an update to the formattedAddress from the search box
const geocoder = new google.maps.Geocoder();
geocoder.geocode(
{
address: newFormattedAddress
},
(results: GeocoderResult[], status: GeocoderStatus) => {
if (status === GeocoderStatus.OK && results.length > 0) {
const firstResult = results[0].geometry;
const bounds = new google.maps.LatLngBounds();
if (firstResult.viewport) {
// Only geocodes have viewport.
bounds.union(firstResult.viewport);
} else {
bounds.extend(firstResult.location);
}
this.map.fitBounds(bounds);
}
}
);
}
External references and credit for the fitBounds code: https://kevinkreuzer.medium.com/how-to-implement-an-address-search-with-angular-and-google-maps-32a2df09f8e9

Categories

Resources